diff options
Diffstat (limited to 'node_modules/webpack')
512 files changed, 34798 insertions, 49904 deletions
diff --git a/node_modules/webpack/LICENSE b/node_modules/webpack/LICENSE index 818e30f71..8c11fc728 100644 --- a/node_modules/webpack/LICENSE +++ b/node_modules/webpack/LICENSE @@ -1,20 +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.
+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. diff --git a/node_modules/webpack/README.md b/node_modules/webpack/README.md index 59a21da77..8ee539501 100644 --- a/node_modules/webpack/README.md +++ b/node_modules/webpack/README.md @@ -1,719 +1,759 @@ -<div align="center">
- <a href="https://github.com/webpack/webpack">
- <img width="200" heigth="200" src="https://webpack.js.org/assets/icon-square-big.svg">
- </a>
- <br>
- <br>
-
-[![npm][npm]][npm-url]
-
-[![node][node]][node-url]
-[![deps][deps]][deps-url]
-[![tests][tests]][tests-url]
-[![builds][builds]][builds-url]
-[![coverage][cover]][cover-url]
-[![licenses][licenses]][licenses-url]
-
- <br>
- <a href="https://npmjs.com/package/webpack">
- <img src="https://img.shields.io/npm/dm/webpack.svg">
- </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://gitter.im/webpack/webpack">
- <img src="https://badges.gitter.im/webpack/webpack.svg">
- </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>
-
-<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>
-
-> This README reflects Webpack v2.x and v3.x. The Webpack v1.x [documentation can be found here](https://webpack.github.io/docs/?utm_source=github&utm_medium=readme&utm_campaign=top).
-
-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](http://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/get-started/) guide and the [other guides](https://webpack.js.org/guides/).
-
-<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|Description|
-|:--:|:----:|:----------|
-|[common-chunks-webpack-plugin][common]|![common-npm]|Generates chunks of common modules shared between entry points and splits them into separate bundles (e.g vendor.bundle.js && app.bundle.js)|
-|[extract-text-webpack-plugin][extract]|![extract-npm]|Extracts Text (CSS) from your bundles into a separate file (app.bundle.css)|
-|[compression-webpack-plugin][compression]|![compression-npm]|Prepare compressed versions of assets to serve them with Content-Encoding|
-|[i18n-webpack-plugin][i18n]|![i18n-npm]|Adds i18n support to your bundles|
-|[html-webpack-plugin][html-plugin]|![html-plugin-npm]| Simplifies creation of HTML files (`index.html`) to serve your bundles|
-
-
-[common]: https://github.com/webpack/webpack/blob/master/lib/optimize/CommonsChunkPlugin.js
-[common-npm]: https://img.shields.io/npm/v/webpack.svg
-[extract]: https://github.com/webpack/extract-text-webpack-plugin
-[extract-npm]: https://img.shields.io/npm/v/extract-text-webpack-plugin.svg
-[component]: https://github.com/webpack/component-webpack-plugin
-[component-npm]: https://img.shields.io/npm/v/component-webpack-plugin.svg
-[compression]: https://github.com/webpack/compression-webpack-plugin
-[compression-npm]: https://img.shields.io/npm/v/compression-webpack-plugin.svg
-[i18n]: https://github.com/webpack/i18n-webpack-plugin
-[i18n-npm]: https://img.shields.io/npm/v/i18n-webpack-plugin.svg
-[html-plugin]: https://github.com/ampedandwired/html-webpack-plugin
-[html-plugin-npm]: https://img.shields.io/npm/v/html-webpack-plugin.svg
-
-### [Loaders](https://webpack.js.org/loaders/)
-
-webpack enables 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|Description|
-|:--:|:----:|:----------|
-|[raw-loader][raw]|![raw-npm]|Loads raw content of a file (utf-8)|
-|[val-loader][val]|![val-npm]|Executes code as module and consider exports as JS code|
-|[url-loader][url]|![url-npm]|Works like the file loader, but can return a Data Url if the file is smaller than a limit|
-|[file-loader][file]|![file-npm]|Emits the file into the output folder and returns the (relative) url|
-
-
-[raw]: https://github.com/webpack/raw-loader
-[raw-npm]: https://img.shields.io/npm/v/raw-loader.svg
-[val]: https://github.com/webpack/val-loader
-[val-npm]: https://img.shields.io/npm/v/val-loader.svg
-[url]: https://github.com/webpack/url-loader
-[url-npm]: https://img.shields.io/npm/v/url-loader.svg
-[file]: https://github.com/webpack/file-loader
-[file-npm]: https://img.shields.io/npm/v/file-loader.svg
-
-#### JSON
-
-|Name|Status|Description|
-|:--:|:----:|:----------|
-|<a href="https://github.com/webpack/json-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/json.svg"></a>|![json-npm]|Loads a JSON file (included by default)|
-|<a href="https://github.com/webpack/json5-loader"><img width="48" height="10.656" src="https://cdn.rawgit.com/json5/json5-logo/master/json5-logo.svg"></a>|![json5-npm]|Loads and transpiles a JSON 5 file|
-|<a href="https://github.com/awnist/cson-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/coffeescript.svg"></a>|![cson-npm]|Loads and transpiles a CSON file|
-
-
-[json-npm]: https://img.shields.io/npm/v/json-loader.svg
-[json5-npm]: https://img.shields.io/npm/v/json5-loader.svg
-[cson-npm]: https://img.shields.io/npm/v/cson-loader.svg
-
-#### Transpiling
-
-|Name|Status|Description|
-|:--:|:----:|:----------|
-|<a href="https://github.com/webpack/script-loader">`<script>`</a>|![script-npm]|Executes a JavaScript file once in global context (like in script tag), requires are not parsed|
-|<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]|Loads ES2015+ code and transpiles to ES5 using <a href="https://github.com/babel/babel">Babel</a>|
-|<a href="https://github.com/jupl/traceur-loader"><img width="48" height="48" src="https://google.github.com/traceur-compiler/logo/tc.svg"></a>|![traceur-npm]|Loads ES2015+ code and transpiles to ES5 using [Traceur](https://github.com/google/traceur-compiler)|
-|<a href="https://github.com/TypeStrong/ts-loader"><img width="48" height="48" src="https://cdn.rawgit.com/Microsoft/TypeScript/master/doc/logo.svg"></a>|![type-npm]|Loads TypeScript like JavaScript|
-|<a href="https://github.com/webpack/coffee-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/coffeescript.svg"></a>|![coffee-npm]|Loads CoffeeScript like JavaScript|
-
-
-[script-npm]: https://img.shields.io/npm/v/script-loader.svg
-[babel-npm]: https://img.shields.io/npm/v/babel-loader.svg
-[traceur-npm]: https://img.shields.io/npm/v/traceur-loader.svg
-[coffee-npm]: https://img.shields.io/npm/v/coffee-loader.svg
-[type-npm]: https://img.shields.io/npm/v/ts-loader.svg
-
-#### Templating
-
-|Name|Status|Description|
-|:--:|:----:|:----------|
-|<a href="https://github.com/webpack/html-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/html5.svg"></a>|![html-npm]|Exports HTML as string, require 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]|Loads Pug templates and returns a function|
-|<a href="https://github.com/webpack/jade-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/jade-3.svg"></a>|![jade-npm]|Loads Jade templates and returns a function|
-|<a href="https://github.com/peerigon/markdown-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/markdown.svg"></a>|![md-npm]|Compiles Markdown to HTML|
-|<a href="https://github.com/posthtml/posthtml-loader"><img width="48" height="48" src="http://posthtml.github.io/posthtml/logo.svg"></a>|![posthtml-npm]|Loads and transforms a HTML file using [PostHTML](https://github.com/posthtml/posthtml)|
-|<a href="https://github.com/altano/handlebars-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/handlebars-1.svg"></a>|![hbs-npm]| Compiles Handlebars to HTML|
-
-
-[html-npm]: https://img.shields.io/npm/v/html-loader.svg
-[pug-npm]: https://img.shields.io/npm/v/pug-loader.svg
-[jade-npm]: https://img.shields.io/npm/v/jade-loader.svg
-[md-npm]: https://img.shields.io/npm/v/markdown-loader.svg
-[posthtml-npm]: https://img.shields.io/npm/v/posthtml-loader.svg
-[hbs-npm]: https://img.shields.io/npm/v/handlebars-loader.svg
-
-#### Styling
-
-|Name|Status|Description|
-|:--:|:----:|:----------|
-|<a href="https://github.com/webpack/style-loader">`<style>`|![style-npm]|Add exports of a module as style to DOM|
-|<a href="https://github.com/webpack/css-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/css-3.svg"></a>|![css-npm]|Loads CSS file with resolved imports and returns CSS code|
-|<a href="https://github.com/webpack/less-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/less-63.svg"></a>|![less-npm]|Loads and compiles a LESS file|
-|<a href="https://github.com/jtangelder/sass-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/sass-1.svg"></a>|![sass-npm]|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]|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]|Loads and transforms a CSS/SSS file using [PostCSS](http://postcss.org)|
-
-
-[style-npm]: https://img.shields.io/npm/v/style-loader.svg
-[css-npm]: https://img.shields.io/npm/v/css-loader.svg
-[less-npm]: https://img.shields.io/npm/v/less-loader.svg
-[sass-npm]: https://img.shields.io/npm/v/sass-loader.svg
-[stylus-npm]: https://img.shields.io/npm/v/stylus-loader.svg
-[postcss-npm]: https://img.shields.io/npm/v/postcss-loader.svg
-
-#### Linting & Testing
-
-|Name|Status|Description|
-|:--:|:----:|:----------|
-|<a href="https://github.com/webpack/mocha-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/mocha.svg"></a>|![mocha-npm]|Tests with mocha (Browser/NodeJS)|
-|<a href="https://github.com/MoOx/eslint-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/eslint.svg"></a>|![eslint-npm]|PreLoader for linting code using ESLint|
-|<a href="https://github.com/webpack-contrib/jshint-loader"><img width="48" height="20.64" src="http://jshint.com/res/jshint-dark.png"></a>|![jshint-npm]|PreLoader for linting code using JSHint|
-
-[mocha-npm]: https://img.shields.io/npm/v/mocha-loader.svg
-[eslint-npm]: https://img.shields.io/npm/v/eslint-loader.svg
-[jshint-npm]: https://img.shields.io/npm/v/jshint-loader.svg
-[jscs-npm]: https://img.shields.io/npm/v/jscs-loader.svg
-
-#### Frameworks
-
-|Name|Status|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]|Loads and compiles Vue Components|
-|<a href="https://github.com/JonDum/polymer-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/polymer.svg"></a>|![polymer-npm]|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]| Loads and compiles Angular 2 Components|
-|<a href="https://github.com/riot/tag-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/riot.svg"></a>|![riot-npm]| Riot official webpack loader|
-
-
-
-[vue-npm]: https://img.shields.io/npm/v/vue-loader.svg
-[polymer-npm]: https://img.shields.io/npm/v/polymer-loader.svg
-[angular-npm]: https://img.shields.io/npm/v/angular2-template-loader.svg
-[riot-npm]: https://img.shields.io/npm/v/riot-tag-loader.svg
-
-### 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](http://github.com/webpack) or [webpack-contrib organization](http://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 repo's!
-* [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).
-
-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 it's 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 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!!
-
-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
-
-[](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 & 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/bebraw.png?s=150">
- <br>
- <a href="https://github.com/bebraw">Juho Vepsäläinen</a>
- <p>Documentation</p>
- <br>
- <p>Author</p>
- <a href="https://leanpub.com/survivejs-webpack">
- <img height="15" src="https://cloud.githubusercontent.com/assets/1365881/20286923/93e325c0-aac9-11e6-964d-cabe218c584c.png">
- </a>
- <br>
- </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">
-
-[Google Angular Team](https://angular.io/), [Architects.io](http://architects.io/),
-<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 sliver 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">Thanks to</h2>
-<p align="center">(In chronological order)</p>
-
-* @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 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 for [browserify](http://browserify.org/), which is a similar project and source for many ideas.
-* @jrburke for [require.js](http://requirejs.org/), which is a similar project and source for many ideas.
-* @defunctzombie for the [browser-field spec](https://gist.github.com/defunctzombie/4339901), 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, @jhnns and @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
-
-[deps]: https://img.shields.io/david/webpack/webpack.svg
-[deps-url]: https://david-dm.org/webpack/webpack
-
-[tests]: https://img.shields.io/travis/webpack/webpack/master.svg
-[tests-url]: https://travis-ci.org/webpack/webpack
-
-[builds-url]: https://ci.appveyor.com/project/sokra/webpack/branch/master
-[builds]: https://ci.appveyor.com/api/projects/status/github/webpack/webpack?svg=true
-
-[licenses-url]: https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fwebpack%2Fwebpack?ref=badge_shield
-[licenses]: https://app.fossa.io/api/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fwebpack%2Fwebpack.svg?type=shield
-
-[cover]: https://img.shields.io/coveralls/webpack/webpack.svg
-[cover-url]: https://coveralls.io/r/webpack/webpack/
+<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] +[![deps][deps]][deps-url] +[![tests][tests]][tests-url] +[![builds][builds]][builds-url] +[![coverage][cover]][cover-url] +[![licenses][licenses]][licenses-url] + + <br> + <a href="https://dependabot.com/compatibility-score.html?dependency-name=webpack&package-manager=npm_and_yarn&new-version=latest"> + <img src="https://api.dependabot.com/badges/compatibility_score?dependency-name=webpack&package-manager=npm_and_yarn&version-scheme=semver&target-version=latest"> + </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.now.sh/result?p=webpack"> + <img src="https://packagephobia.now.sh/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://gitter.im/webpack/webpack"> + <img src="https://badges.gitter.im/webpack/webpack.svg"> + </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> + +<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](http://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/get-started/) guide and the [other guides](https://webpack.js.org/guides/). + +### Browser Compatibility + +webpack supports all browsers that are [ES5-compliant](http://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| +|[i18n-webpack-plugin][i18n]|![i18n-npm]|![i18n-size]|Adds i18n support to your bundles| +|[html-webpack-plugin][html-plugin]|![html-plugin-npm]|![html-plugin-size]| Simplifies creation of HTML files (`index.html`) to serve your bundles| +|[extract-text-webpack-plugin][extract]|![extract-npm]|![extract-size]|Extract text from a bundle, or bundles, into a separate file| + +[common-npm]: https://img.shields.io/npm/v/webpack.svg +[extract]: https://github.com/webpack/extract-text-webpack-plugin +[extract-npm]: https://img.shields.io/npm/v/extract-text-webpack-plugin.svg +[extract-size]: https://packagephobia.now.sh/badge?p=extract-text-webpack-plugin +[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.now.sh/badge?p=mini-css-extract-plugin +[component]: https://github.com/webpack/component-webpack-plugin +[component-npm]: https://img.shields.io/npm/v/component-webpack-plugin.svg +[component-size]: https://packagephobia.now.sh/badge?p=component-webpack-plugin +[compression]: https://github.com/webpack/compression-webpack-plugin +[compression-npm]: https://img.shields.io/npm/v/compression-webpack-plugin.svg +[compression-size]: https://packagephobia.now.sh/badge?p=compression-webpack-plugin +[i18n]: https://github.com/webpack/i18n-webpack-plugin +[i18n-npm]: https://img.shields.io/npm/v/i18n-webpack-plugin.svg +[i18n-size]: https://packagephobia.now.sh/badge?p=i18n-webpack-plugin +[html-plugin]: https://github.com/ampedandwired/html-webpack-plugin +[html-plugin-npm]: https://img.shields.io/npm/v/html-webpack-plugin.svg +[html-plugin-size]: https://packagephobia.now.sh/badge?p=html-webpack-plugin + +### [Loaders](https://webpack.js.org/loaders/) + +webpack enables 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| +|:--:|:----:|:----------:|:----------| +|[raw-loader][raw]|![raw-npm]|![raw-size]|Loads raw content of a file (utf-8)| +|[val-loader][val]|![val-npm]|![val-size]|Executes code as module and considers exports as JS code| +|[url-loader][url]|![url-npm]|![url-size]|Works like the file loader, but can return a Data Url if the file is smaller than a limit| +|[file-loader][file]|![file-npm]|![file-size]|Emits the file into the output folder and returns the (relative) url| + + +[raw]: https://github.com/webpack/raw-loader +[raw-npm]: https://img.shields.io/npm/v/raw-loader.svg +[raw-size]: https://packagephobia.now.sh/badge?p=raw-loader +[val]: https://github.com/webpack/val-loader +[val-npm]: https://img.shields.io/npm/v/val-loader.svg +[val-size]: https://packagephobia.now.sh/badge?p=val-loader +[url]: https://github.com/webpack/url-loader +[url-npm]: https://img.shields.io/npm/v/url-loader.svg +[url-size]: https://packagephobia.now.sh/badge?p=url-loader +[file]: https://github.com/webpack/file-loader +[file-npm]: https://img.shields.io/npm/v/file-loader.svg +[file-size]: https://packagephobia.now.sh/badge?p=file-loader + +#### JSON + +|Name|Status|Install Size|Description| +|:--:|:----:|:----------:|:----------| +|<a href="https://github.com/webpack/json-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/json.svg"></a>|![json-npm]|![json-size]|Loads a JSON file (included by default)| +|<a href="https://github.com/webpack/json5-loader"><img width="48" height="10.656" src="https://cdn.rawgit.com/json5/json5-logo/master/json5-logo.svg"></a>|![json5-npm]|![json5-size]|Loads and transpiles a JSON 5 file| +|<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| + + +[json-npm]: https://img.shields.io/npm/v/json-loader.svg +[json-size]: https://packagephobia.now.sh/badge?p=json-loader +[json5-npm]: https://img.shields.io/npm/v/json5-loader.svg +[json5-size]: https://packagephobia.now.sh/badge?p=json5-loader +[cson-npm]: https://img.shields.io/npm/v/cson-loader.svg +[cson-size]: https://packagephobia.now.sh/badge?p=cson-loader + +#### Transpiling + +|Name|Status|Install Size|Description| +|:--:|:----:|:----------:|:----------| +|<a href="https://github.com/webpack/script-loader">`<script>`</a>|![script-npm]|![script-size]|Executes a JavaScript file once in global context (like in script tag), `require()`s are not parsed| +|<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/jupl/traceur-loader"><img width="48" height="48" src="https://google.github.com/traceur-compiler/logo/tc.svg"></a>|![traceur-npm]|![traceur-size]|Loads ES2015+ code and transpiles to ES5 using [Traceur](https://github.com/google/traceur-compiler)| +|<a href="https://github.com/TypeStrong/ts-loader"><img width="48" height="48" src="https://cdn.rawgit.com/Microsoft/TypeScript/master/doc/logo.svg"></a>|![type-npm]|![type-size]|Loads TypeScript like JavaScript| +|[`awesome-typescript-loader`](https://github.com/s-panferov/awesome-typescript-loader)|![awesome-typescript-npm]|![awesome-typescript-size]|Awesome TypeScript loader for webpack| +|<a href="https://github.com/webpack/coffee-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/coffeescript.svg"></a>|![coffee-npm]|![coffee-size]|Loads CoffeeScript like JavaScript| + + +[script-npm]: https://img.shields.io/npm/v/script-loader.svg +[script-size]: https://packagephobia.now.sh/badge?p=script-loader +[babel-npm]: https://img.shields.io/npm/v/babel-loader.svg +[babel-size]: https://packagephobia.now.sh/badge?p=babel-loader +[traceur-npm]: https://img.shields.io/npm/v/traceur-loader.svg +[traceur-size]: https://packagephobia.now.sh/badge?p=traceur-loader +[coffee-npm]: https://img.shields.io/npm/v/coffee-loader.svg +[coffee-size]: https://packagephobia.now.sh/badge?p=coffee-loader +[type-npm]: https://img.shields.io/npm/v/ts-loader.svg +[type-size]: https://packagephobia.now.sh/badge?p=ts-loader +[awesome-typescript-npm]: https://img.shields.io/npm/v/awesome-typescript-loader.svg +[awesome-typescript-size]: https://packagephobia.now.sh/badge?p=awesome-typescript-loader + +#### Templating + +|Name|Status|Install Size|Description| +|:--:|:----:|:----------:|:----------| +|<a href="https://github.com/webpack/html-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/html5.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/webpack/jade-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/jade-3.svg"></a>|![jade-npm]|![jade-size]|Loads Jade templates and returns a function| +|<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="http://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/altano/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.now.sh/badge?p=html-loader +[pug-npm]: https://img.shields.io/npm/v/pug-loader.svg +[pug-size]: https://packagephobia.now.sh/badge?p=pug-loader +[jade-npm]: https://img.shields.io/npm/v/jade-loader.svg +[jade-size]: https://packagephobia.now.sh/badge?p=jade-loader +[md-npm]: https://img.shields.io/npm/v/markdown-loader.svg +[md-size]: https://packagephobia.now.sh/badge?p=markdown-loader +[posthtml-npm]: https://img.shields.io/npm/v/posthtml-loader.svg +[posthtml-size]: https://packagephobia.now.sh/badge?p=posthtml-loader +[hbs-npm]: https://img.shields.io/npm/v/handlebars-loader.svg +[hbs-size]: https://packagephobia.now.sh/badge?p=handlebars-loader + +#### Styling + +|Name|Status|Install Size|Description| +|:--:|:----:|:----------:|:----------| +|<a href="https://github.com/webpack/style-loader">`<style>`</a>|![style-npm]|![style-size]|Add exports of a module as style to DOM| +|<a href="https://github.com/webpack/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/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/jtangelder/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](http://postcss.org)| + + +[style-npm]: https://img.shields.io/npm/v/style-loader.svg +[style-size]: https://packagephobia.now.sh/badge?p=style-loader +[css-npm]: https://img.shields.io/npm/v/css-loader.svg +[css-size]: https://packagephobia.now.sh/badge?p=css-loader +[less-npm]: https://img.shields.io/npm/v/less-loader.svg +[less-size]: https://packagephobia.now.sh/badge?p=less-loader +[sass-npm]: https://img.shields.io/npm/v/sass-loader.svg +[sass-size]: https://packagephobia.now.sh/badge?p=sass-loader +[stylus-npm]: https://img.shields.io/npm/v/stylus-loader.svg +[stylus-size]: https://packagephobia.now.sh/badge?p=stylus-loader +[postcss-npm]: https://img.shields.io/npm/v/postcss-loader.svg +[postcss-size]: https://packagephobia.now.sh/badge?p=postcss-loader + +#### Linting & Testing + +|Name|Status|Install Size|Description| +|:--:|:----:|:----------:|:----------| +|<a href="https://github.com/webpack/mocha-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/mocha.svg"></a>|![mocha-npm]|![mocha-size]|Tests with mocha (Browser/NodeJS)| +|<a href="https://github.com/MoOx/eslint-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/eslint.svg"></a>|![eslint-npm]|![eslint-size]|PreLoader for linting code using ESLint| +|<a href="https://github.com/webpack-contrib/jshint-loader"><img width="48" height="20.64" src="http://jshint.com/res/jshint-dark.png"></a>|![jshint-npm]|![jshint-size]|PreLoader for linting code using JSHint| + +[mocha-npm]: https://img.shields.io/npm/v/mocha-loader.svg +[mocha-size]: https://packagephobia.now.sh/badge?p=mocha-loader +[eslint-npm]: https://img.shields.io/npm/v/eslint-loader.svg +[eslint-size]: https://packagephobia.now.sh/badge?p=eslint-loader +[jshint-npm]: https://img.shields.io/npm/v/jshint-loader.svg +[jshint-size]: https://packagephobia.now.sh/badge?p=jshint-loader +[jscs-npm]: https://img.shields.io/npm/v/jscs-loader.svg +[jscs-size]: https://packagephobia.now.sh/badge?p=jscs-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/tag-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/riot.svg"></a>|![riot-npm]|![riot-size]| Riot official webpack loader| + + + +[vue-npm]: https://img.shields.io/npm/v/vue-loader.svg +[vue-size]: https://packagephobia.now.sh/badge?p=vue-loader +[polymer-npm]: https://img.shields.io/npm/v/polymer-webpack-loader.svg +[polymer-size]: https://packagephobia.now.sh/badge?p=polymer-webpack-loader +[angular-npm]: https://img.shields.io/npm/v/angular2-template-loader.svg +[angular-size]: https://packagephobia.now.sh/badge?p=angular2-template-loader +[riot-npm]: https://img.shields.io/npm/v/riot-tag-loader.svg +[riot-size]: https://packagephobia.now.sh/badge?p=riot-tag-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](http://github.com/webpack) or [webpack-contrib organization](http://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). + +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 it's 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 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 + +[](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 & 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"> + +[Google Angular Team](https://angular.io/), [Architects.io](http://architects.io/), +<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">Thanks to</h2> +<p align="center">(In chronological order)</p> + +* @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 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 for [browserify](http://browserify.org/), which is a similar project and source for many ideas. +* @jrburke for [require.js](http://requirejs.org/), which is a similar project and source for many ideas. +* @defunctzombie for the [browser-field spec](https://gist.github.com/defunctzombie/4339901), 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, @jhnns and @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 + +[deps]: https://img.shields.io/david/webpack/webpack.svg +[deps-url]: https://david-dm.org/webpack/webpack + +[tests]: https://img.shields.io/travis/webpack/webpack/master.svg +[tests-url]: https://travis-ci.org/webpack/webpack + +[builds-url]: https://ci.appveyor.com/project/sokra/webpack/branch/master +[builds]: https://ci.appveyor.com/api/projects/status/github/webpack/webpack?svg=true + +[licenses-url]: https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fwebpack%2Fwebpack?ref=badge_shield +[licenses]: https://app.fossa.io/api/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fwebpack%2Fwebpack.svg?type=shield + +[cover]: https://img.shields.io/coveralls/webpack/webpack.svg +[cover-url]: https://coveralls.io/r/webpack/webpack/ diff --git a/node_modules/webpack/bin/config-optimist.js b/node_modules/webpack/bin/config-optimist.js deleted file mode 100644 index 6ec4d62c8..000000000 --- a/node_modules/webpack/bin/config-optimist.js +++ /dev/null @@ -1,48 +0,0 @@ -module.exports = function(optimist) { - optimist - .boolean("help").alias("help", "h").alias("help", "?").describe("help") - .string("config").describe("config", "Path to the config file") - .string("config-name").describe("config-name", "Name of the config to use") - .string("env").describe("env", "Environment passed to the config, when it is a function") - .string("context").describe("context", "The root directory for resolving entry point and stats") - .string("entry").describe("entry", "The entry point") - .string("module-bind").describe("module-bind", "Bind an extension to a loader") - .string("module-bind-post").describe("module-bind-post") - .string("module-bind-pre").describe("module-bind-pre") - .string("output-path").describe("output-path", "The output path for compilation assets") - .string("output-filename").describe("output-filename", "The output filename of the bundle") - .string("output-chunk-filename").describe("output-chunk-filename", "The output filename for additional chunks") - .string("output-source-map-filename").describe("output-source-map-filename", "The output filename for the SourceMap") - .string("output-public-path").describe("output-public-path", "The public path for the assets") - .string("output-jsonp-function").describe("output-jsonp-function", "The name of the jsonp function used for chunk loading") - .boolean("output-pathinfo").describe("output-pathinfo", "Include a comment with the request for every dependency") - .string("output-library").describe("output-library", "Expose the exports of the entry point as library") - .string("output-library-target").describe("output-library-target", "The type for exposing the exports of the entry point as library") - .string("records-input-path").describe("records-input-path", "Path to the records file (reading)") - .string("records-output-path").describe("records-output-path", "Path to the records file (writing)") - .string("records-path").describe("records-path", "Path to the records file") - .string("define").describe("define", "Define any free var in the bundle") - .string("target").describe("target", "The targeted execution environment") - .boolean("cache").describe("cache", "Enable in memory caching").default("cache", true) - .boolean("watch").alias("watch", "w").describe("watch", "Watch the filesystem for changes") - .boolean("watch-stdin").alias("watch-stdin", "stdin").describe("Exit the process when stdin is closed") - .describe("watch-aggregate-timeout", "Timeout for gathering changes while watching") - .describe("watch-poll", "The polling interval for watching (also enable polling)") - .boolean("hot").describe("hot", "Enables Hot Module Replacement") - .boolean("debug").describe("debug", "Switch loaders to debug mode") - .string("devtool").describe("devtool", "Enable devtool for better debugging experience") - .boolean("progress").describe("progress", "Print compilation progress in percentage") - .string("resolve-alias").describe("resolve-alias", "Setup a module alias for resolving") - .string("resolve-extensions").describe("resolve-extensions", "Setup extensions that should be used to resolve modules") - .string("resolve-loader-alias").describe("resolve-loader-alias", "Setup a loader alias for resolving") - .describe("optimize-max-chunks", "Try to keep the chunk count below a limit") - .describe("optimize-min-chunk-size", "Try to keep the chunk size above a limit") - .boolean("optimize-minimize").describe("optimize-minimize", "Minimize javascript and switches loaders to minimizing") - .string("prefetch").describe("prefetch", "Prefetch this request") - .string("provide").describe("provide", "Provide these modules as free vars in all modules") - .string("plugin").describe("plugin", "Load this plugin") - .boolean("bail").describe("bail", "Abort the compilation on first error") - .boolean("profile").describe("profile", "Profile the compilation and include information in stats") - .boolean("d").describe("d", "shortcut for --debug --devtool eval-check-module-source-map --output-pathinfo") - .boolean("p").describe("p", "shortcut for --optimize-minimize --define process.env.NODE_ENV=\"production\""); -}; diff --git a/node_modules/webpack/bin/config-yargs.js b/node_modules/webpack/bin/config-yargs.js deleted file mode 100644 index 0f44fdebe..000000000 --- a/node_modules/webpack/bin/config-yargs.js +++ /dev/null @@ -1,274 +0,0 @@ -var CONFIG_GROUP = "Config options:"; -var BASIC_GROUP = "Basic options:"; -var MODULE_GROUP = "Module options:"; -var OUTPUT_GROUP = "Output options:"; -var ADVANCED_GROUP = "Advanced options:"; -var RESOLVE_GROUP = "Resolving options:"; -var OPTIMIZE_GROUP = "Optimizing options:"; - -module.exports = function(yargs) { - yargs - .help("help") - .alias("help", "h") - .version() - .alias("version", "v") - .options({ - "config": { - type: "string", - describe: "Path to the config file", - group: CONFIG_GROUP, - defaultDescription: "webpack.config.js or webpackfile.js", - requiresArg: true - }, - "config-name": { - type: "string", - describe: "Name of the config to use", - group: CONFIG_GROUP, - requiresArg: true - }, - "env": { - describe: "Environment passed to the config, when it is a function", - group: CONFIG_GROUP - }, - "context": { - type: "string", - describe: "The root directory for resolving entry point and stats", - group: BASIC_GROUP, - defaultDescription: "The current directory", - requiresArg: true - }, - "entry": { - type: "string", - describe: "The entry point", - group: BASIC_GROUP, - requiresArg: true - }, - "module-bind": { - type: "string", - describe: "Bind an extension to a loader", - group: MODULE_GROUP, - requiresArg: true - }, - "module-bind-post": { - type: "string", - describe: "", - group: MODULE_GROUP, - requiresArg: true - }, - "module-bind-pre": { - type: "string", - describe: "", - group: MODULE_GROUP, - requiresArg: true - }, - "output-path": { - type: "string", - describe: "The output path for compilation assets", - group: OUTPUT_GROUP, - defaultDescription: "The current directory", - requiresArg: true - }, - "output-filename": { - type: "string", - describe: "The output filename of the bundle", - group: OUTPUT_GROUP, - defaultDescription: "[name].js", - requiresArg: true - }, - "output-chunk-filename": { - type: "string", - describe: "The output filename for additional chunks", - group: OUTPUT_GROUP, - defaultDescription: "filename with [id] instead of [name] or [id] prefixed", - requiresArg: true - }, - "output-source-map-filename": { - type: "string", - describe: "The output filename for the SourceMap", - group: OUTPUT_GROUP, - requiresArg: true - }, - "output-public-path": { - type: "string", - describe: "The public path for the assets", - group: OUTPUT_GROUP, - requiresArg: true - }, - "output-jsonp-function": { - type: "string", - describe: "The name of the jsonp function used for chunk loading", - group: OUTPUT_GROUP, - requiresArg: true - }, - "output-pathinfo": { - type: "boolean", - describe: "Include a comment with the request for every dependency (require, import, etc.)", - group: OUTPUT_GROUP - }, - "output-library": { - type: "string", - describe: "Expose the exports of the entry point as library", - group: OUTPUT_GROUP, - requiresArg: true - }, - "output-library-target": { - type: "string", - describe: "The type for exposing the exports of the entry point as library", - group: OUTPUT_GROUP, - requiresArg: true - }, - "records-input-path": { - type: "string", - describe: "Path to the records file (reading)", - group: ADVANCED_GROUP, - requiresArg: true - }, - "records-output-path": { - type: "string", - describe: "Path to the records file (writing)", - group: ADVANCED_GROUP, - requiresArg: true - }, - "records-path": { - type: "string", - describe: "Path to the records file", - group: ADVANCED_GROUP, - requiresArg: true - }, - "define": { - type: "string", - describe: "Define any free var in the bundle", - group: ADVANCED_GROUP, - requiresArg: true - }, - "target": { - type: "string", - describe: "The targeted execution environment", - group: ADVANCED_GROUP, - requiresArg: true - }, - "cache": { - type: "boolean", - describe: "Enable in memory caching", - default: null, - group: ADVANCED_GROUP, - defaultDescription: "It's enabled by default when watching" - }, - "watch": { - type: "boolean", - alias: "w", - describe: "Watch the filesystem for changes", - group: BASIC_GROUP - }, - "watch-stdin": { - type: "boolean", - alias: "stdin", - describe: "Exit the process when stdin is closed", - group: ADVANCED_GROUP - }, - "watch-aggregate-timeout": { - describe: "Timeout for gathering changes while watching", - group: ADVANCED_GROUP, - requiresArg: true - }, - "watch-poll": { - type: "string", - describe: "The polling interval for watching (also enable polling)", - group: ADVANCED_GROUP - }, - "hot": { - type: "boolean", - describe: "Enables Hot Module Replacement", - group: ADVANCED_GROUP - }, - "debug": { - type: "boolean", - describe: "Switch loaders to debug mode", - group: BASIC_GROUP - }, - "devtool": { - type: "string", - describe: "Enable devtool for better debugging experience (Example: --devtool eval-cheap-module-source-map)", - group: BASIC_GROUP, - requiresArg: true - }, - "resolve-alias": { - type: "string", - describe: "Setup a module alias for resolving (Example: jquery-plugin=jquery.plugin)", - group: RESOLVE_GROUP, - requiresArg: true - }, - "resolve-extensions": { - "type": "array", - describe: "Setup extensions that should be used to resolve modules (Example: --resolve-extensions .es6,.js)", - group: RESOLVE_GROUP, - requiresArg: true - }, - "resolve-loader-alias": { - type: "string", - describe: "Setup a loader alias for resolving", - group: RESOLVE_GROUP, - requiresArg: true - }, - "optimize-max-chunks": { - describe: "Try to keep the chunk count below a limit", - group: OPTIMIZE_GROUP, - requiresArg: true - }, - "optimize-min-chunk-size": { - describe: "Try to keep the chunk size above a limit", - group: OPTIMIZE_GROUP, - requiresArg: true - }, - "optimize-minimize": { - type: "boolean", - describe: "Minimize javascript and switches loaders to minimizing", - group: OPTIMIZE_GROUP - }, - "prefetch": { - type: "string", - describe: "Prefetch this request (Example: --prefetch ./file.js)", - group: ADVANCED_GROUP, - requiresArg: true - }, - "provide": { - type: "string", - describe: "Provide these modules as free vars in all modules (Example: --provide jQuery=jquery)", - group: ADVANCED_GROUP, - requiresArg: true - }, - "labeled-modules": { - type: "boolean", - describe: "Enables labeled modules", - group: ADVANCED_GROUP - }, - "plugin": { - type: "string", - describe: "Load this plugin", - group: ADVANCED_GROUP, - requiresArg: true - }, - "bail": { - type: "boolean", - describe: "Abort the compilation on first error", - group: ADVANCED_GROUP, - default: null - }, - "profile": { - type: "boolean", - describe: "Profile the compilation and include information in stats", - group: ADVANCED_GROUP, - default: null - }, - "d": { - type: "boolean", - describe: "shortcut for --debug --devtool eval-cheap-module-source-map --output-pathinfo", - group: BASIC_GROUP - }, - "p": { - type: "boolean", - describe: "shortcut for --optimize-minimize --define process.env.NODE_ENV=\"production\"", - group: BASIC_GROUP - } - }).strict(); -}; diff --git a/node_modules/webpack/bin/convert-argv.js b/node_modules/webpack/bin/convert-argv.js deleted file mode 100644 index db68f76a6..000000000 --- a/node_modules/webpack/bin/convert-argv.js +++ /dev/null @@ -1,562 +0,0 @@ -var path = require("path"); -var fs = require("fs"); -fs.existsSync = fs.existsSync || path.existsSync; -var interpret = require("interpret"); -var prepareOptions = require("../lib/prepareOptions"); - -module.exports = function(yargs, argv, convertOptions) { - - var options = []; - - // Shortcuts - if(argv.d) { - argv.debug = true; - argv["output-pathinfo"] = true; - if(!argv.devtool) { - argv.devtool = "eval-cheap-module-source-map"; - } - } - if(argv.p) { - argv["optimize-minimize"] = true; - argv["define"] = [].concat(argv["define"] || []).concat("process.env.NODE_ENV=\"production\""); - } - - var configFileLoaded = false; - var configFiles = []; - var extensions = Object.keys(interpret.extensions).sort(function(a, b) { - return a === ".js" ? -1 : b === ".js" ? 1 : a.length - b.length; - }); - var defaultConfigFiles = ["webpack.config", "webpackfile"].map(function(filename) { - return extensions.map(function(ext) { - return { - path: path.resolve(filename + ext), - ext: ext - }; - }); - }).reduce(function(a, i) { - return a.concat(i); - }, []); - - var i; - if(argv.config) { - var getConfigExtension = function getConfigExtension(configPath) { - for(i = extensions.length - 1; i >= 0; i--) { - var tmpExt = extensions[i]; - if(configPath.indexOf(tmpExt, configPath.length - tmpExt.length) > -1) { - return tmpExt; - } - } - return path.extname(configPath); - }; - - var mapConfigArg = function mapConfigArg(configArg) { - var resolvedPath = path.resolve(configArg); - var extension = getConfigExtension(resolvedPath); - return { - path: resolvedPath, - ext: extension - }; - }; - - var configArgList = Array.isArray(argv.config) ? argv.config : [argv.config]; - configFiles = configArgList.map(mapConfigArg); - } else { - for(i = 0; i < defaultConfigFiles.length; i++) { - var webpackConfig = defaultConfigFiles[i].path; - if(fs.existsSync(webpackConfig)) { - configFiles.push({ - path: webpackConfig, - ext: defaultConfigFiles[i].ext - }); - break; - } - } - } - - if(configFiles.length > 0) { - var registerCompiler = function registerCompiler(moduleDescriptor) { - if(moduleDescriptor) { - if(typeof moduleDescriptor === "string") { - require(moduleDescriptor); - } else if(!Array.isArray(moduleDescriptor)) { - moduleDescriptor.register(require(moduleDescriptor.module)); - } else { - for(var i = 0; i < moduleDescriptor.length; i++) { - try { - registerCompiler(moduleDescriptor[i]); - break; - } catch(e) { - // do nothing - } - } - } - } - }; - - var requireConfig = function requireConfig(configPath) { - var options = require(configPath); - options = prepareOptions(options, argv); - return options; - }; - - configFiles.forEach(function(file) { - registerCompiler(interpret.extensions[file.ext]); - options.push(requireConfig(file.path)); - }); - configFileLoaded = true; - } - - if(!configFileLoaded) { - return processConfiguredOptions({}); - } else if(options.length === 1) { - return processConfiguredOptions(options[0]); - } else { - return processConfiguredOptions(options); - } - - function processConfiguredOptions(options) { - if(options === null || typeof options !== "object") { - console.error("Config did not export an object or a function returning an object."); - process.exit(-1); // eslint-disable-line - } - - // process Promise - if(typeof options.then === "function") { - return options.then(processConfiguredOptions); - } - - // process ES6 default - if(typeof options === "object" && typeof options.default === "object") { - return processConfiguredOptions(options.default); - } - - // filter multi-config by name - if(Array.isArray(options) && argv["config-name"]) { - var namedOptions = options.filter(function(opt) { - return opt.name === argv["config-name"]; - }); - if(namedOptions.length === 0) { - console.error("Configuration with name '" + argv["config-name"] + "' was not found."); - process.exit(-1); // eslint-disable-line - } else if(namedOptions.length === 1) { - return processConfiguredOptions(namedOptions[0]); - } - options = namedOptions; - } - - if(Array.isArray(options)) { - options.forEach(processOptions); - } else { - processOptions(options); - } - - if(argv.context) { - options.context = path.resolve(argv.context); - } - if(!options.context) { - options.context = process.cwd(); - } - - if(argv.watch) { - options.watch = true; - } - - if(argv["watch-aggregate-timeout"]) { - options.watchOptions = options.watchOptions || {}; - options.watchOptions.aggregateTimeout = +argv["watch-aggregate-timeout"]; - } - - if(typeof argv["watch-poll"] !== "undefined") { - options.watchOptions = options.watchOptions || {}; - if(argv["watch-poll"] === "true" || argv["watch-poll"] === "") - options.watchOptions.poll = true; - else if(!isNaN(argv["watch-poll"])) - options.watchOptions.poll = +argv["watch-poll"]; - } - - if(argv["watch-stdin"]) { - options.watchOptions = options.watchOptions || {}; - options.watchOptions.stdin = true; - options.watch = true; - } - - return options; - } - - function processOptions(options) { - var noOutputFilenameDefined = !options.output || !options.output.filename; - - function ifArg(name, fn, init, finalize) { - if(Array.isArray(argv[name])) { - if(init) { - init(); - } - argv[name].forEach(fn); - if(finalize) { - finalize(); - } - } else if(typeof argv[name] !== "undefined" && argv[name] !== null) { - if(init) { - init(); - } - fn(argv[name], -1); - if(finalize) { - finalize(); - } - } - } - - function ifArgPair(name, fn, init, finalize) { - ifArg(name, function(content, idx) { - var i = content.indexOf("="); - if(i < 0) { - return fn(null, content, idx); - } else { - return fn(content.substr(0, i), content.substr(i + 1), idx); - } - }, init, finalize); - } - - function ifBooleanArg(name, fn) { - ifArg(name, function(bool) { - if(bool) { - fn(); - } - }); - } - - function mapArgToBoolean(name, optionName) { - ifArg(name, function(bool) { - if(bool === true) - options[optionName || name] = true; - else if(bool === false) - options[optionName || name] = false; - }); - } - - function loadPlugin(name) { - var loadUtils = require("loader-utils"); - var args; - try { - var p = name && name.indexOf("?"); - if(p > -1) { - args = loadUtils.parseQuery(name.substring(p)); - name = name.substring(0, p); - } - } catch(e) { - console.log("Invalid plugin arguments " + name + " (" + e + ")."); - process.exit(-1); // eslint-disable-line - } - - var path; - try { - var resolve = require("enhanced-resolve"); - path = resolve.sync(process.cwd(), name); - } catch(e) { - console.log("Cannot resolve plugin " + name + "."); - process.exit(-1); // eslint-disable-line - } - var Plugin; - try { - Plugin = require(path); - } catch(e) { - console.log("Cannot load plugin " + name + ". (" + path + ")"); - throw e; - } - try { - return new Plugin(args); - } catch(e) { - console.log("Cannot instantiate plugin " + name + ". (" + path + ")"); - throw e; - } - } - - function ensureObject(parent, name) { - if(typeof parent[name] !== "object" || parent[name] === null) { - parent[name] = {}; - } - } - - function ensureArray(parent, name) { - if(!Array.isArray(parent[name])) { - parent[name] = []; - } - } - - ifArgPair("entry", function(name, entry) { - if(typeof options.entry[name] !== "undefined" && options.entry[name] !== null) { - options.entry[name] = [].concat(options.entry[name]).concat(entry); - } else { - options.entry[name] = entry; - } - }, function() { - ensureObject(options, "entry"); - }); - - function bindRules(arg) { - ifArgPair(arg, function(name, binding) { - if(name === null) { - name = binding; - binding += "-loader"; - } - var rule = { - test: new RegExp("\\." + name.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&") + "$"), // eslint-disable-line no-useless-escape - loader: binding - }; - if(arg === "module-bind-pre") { - rule.enforce = "pre"; - } else if(arg === "module-bind-post") { - rule.enforce = "post"; - } - options.module.rules.push(rule); - }, function() { - ensureObject(options, "module"); - ensureArray(options.module, "rules"); - }); - } - bindRules("module-bind"); - bindRules("module-bind-pre"); - bindRules("module-bind-post"); - - var defineObject; - ifArgPair("define", function(name, value) { - if(name === null) { - name = value; - value = true; - } - defineObject[name] = value; - }, function() { - defineObject = {}; - }, function() { - ensureArray(options, "plugins"); - var DefinePlugin = require("../lib/DefinePlugin"); - options.plugins.push(new DefinePlugin(defineObject)); - }); - - ifArg("output-path", function(value) { - ensureObject(options, "output"); - options.output.path = path.resolve(value); - }); - - ifArg("output-filename", function(value) { - ensureObject(options, "output"); - options.output.filename = value; - noOutputFilenameDefined = false; - }); - - ifArg("output-chunk-filename", function(value) { - ensureObject(options, "output"); - options.output.chunkFilename = value; - }); - - ifArg("output-source-map-filename", function(value) { - ensureObject(options, "output"); - options.output.sourceMapFilename = value; - }); - - ifArg("output-public-path", function(value) { - ensureObject(options, "output"); - options.output.publicPath = value; - }); - - ifArg("output-jsonp-function", function(value) { - ensureObject(options, "output"); - options.output.jsonpFunction = value; - }); - - ifBooleanArg("output-pathinfo", function() { - ensureObject(options, "output"); - options.output.pathinfo = true; - }); - - ifArg("output-library", function(value) { - ensureObject(options, "output"); - options.output.library = value; - }); - - ifArg("output-library-target", function(value) { - ensureObject(options, "output"); - options.output.libraryTarget = value; - }); - - ifArg("records-input-path", function(value) { - options.recordsInputPath = path.resolve(value); - }); - - ifArg("records-output-path", function(value) { - options.recordsOutputPath = path.resolve(value); - }); - - ifArg("records-path", function(value) { - options.recordsPath = path.resolve(value); - }); - - ifArg("target", function(value) { - options.target = value; - }); - - mapArgToBoolean("cache"); - - ifBooleanArg("hot", function() { - ensureArray(options, "plugins"); - var HotModuleReplacementPlugin = require("../lib/HotModuleReplacementPlugin"); - options.plugins.push(new HotModuleReplacementPlugin()); - }); - - ifBooleanArg("debug", function() { - ensureArray(options, "plugins"); - var LoaderOptionsPlugin = require("../lib/LoaderOptionsPlugin"); - options.plugins.push(new LoaderOptionsPlugin({ - debug: true - })); - }); - - ifArg("devtool", function(value) { - options.devtool = value; - }); - - function processResolveAlias(arg, key) { - ifArgPair(arg, function(name, value) { - if(!name) { - throw new Error("--" + arg + " <string>=<string>"); - } - ensureObject(options, key); - ensureObject(options[key], "alias"); - options[key].alias[name] = value; - }); - } - processResolveAlias("resolve-alias", "resolve"); - processResolveAlias("resolve-loader-alias", "resolveLoader"); - - ifArg("resolve-extensions", function(value) { - ensureObject(options, "resolve"); - if(Array.isArray(value)) { - options.resolve.extensions = value; - } else { - options.resolve.extensions = value.split(/,\s*/); - } - }); - - ifArg("optimize-max-chunks", function(value) { - ensureArray(options, "plugins"); - var LimitChunkCountPlugin = require("../lib/optimize/LimitChunkCountPlugin"); - options.plugins.push(new LimitChunkCountPlugin({ - maxChunks: parseInt(value, 10) - })); - }); - - ifArg("optimize-min-chunk-size", function(value) { - ensureArray(options, "plugins"); - var MinChunkSizePlugin = require("../lib/optimize/MinChunkSizePlugin"); - options.plugins.push(new MinChunkSizePlugin({ - minChunkSize: parseInt(value, 10) - })); - }); - - ifBooleanArg("optimize-minimize", function() { - ensureArray(options, "plugins"); - var UglifyJsPlugin = require("../lib/optimize/UglifyJsPlugin"); - var LoaderOptionsPlugin = require("../lib/LoaderOptionsPlugin"); - options.plugins.push(new UglifyJsPlugin({ - sourceMap: options.devtool && (options.devtool.indexOf("sourcemap") >= 0 || options.devtool.indexOf("source-map") >= 0) - })); - options.plugins.push(new LoaderOptionsPlugin({ - minimize: true - })); - }); - - ifArg("prefetch", function(request) { - ensureArray(options, "plugins"); - var PrefetchPlugin = require("../lib/PrefetchPlugin"); - options.plugins.push(new PrefetchPlugin(request)); - }); - - ifArg("provide", function(value) { - ensureArray(options, "plugins"); - var idx = value.indexOf("="); - var name; - if(idx >= 0) { - name = value.substr(0, idx); - value = value.substr(idx + 1); - } else { - name = value; - } - var ProvidePlugin = require("../lib/ProvidePlugin"); - options.plugins.push(new ProvidePlugin(name, value)); - }); - - ifArg("plugin", function(value) { - ensureArray(options, "plugins"); - options.plugins.push(loadPlugin(value)); - }); - - mapArgToBoolean("bail"); - - mapArgToBoolean("profile"); - - if(noOutputFilenameDefined) { - ensureObject(options, "output"); - if(convertOptions && convertOptions.outputFilename) { - options.output.path = path.resolve(path.dirname(convertOptions.outputFilename)); - options.output.filename = path.basename(convertOptions.outputFilename); - } else if(argv._.length > 0) { - options.output.filename = argv._.pop(); - options.output.path = path.resolve(path.dirname(options.output.filename)); - options.output.filename = path.basename(options.output.filename); - } else if(configFileLoaded) { - throw new Error("'output.filename' is required, either in config file or as --output-filename"); - } else { - console.error("No configuration file found and no output filename configured via CLI option."); - console.error("A configuration file could be named 'webpack.config.js' in the current directory."); - console.error("Use --help to display the CLI options."); - process.exit(-1); // eslint-disable-line - } - } - - if(argv._.length > 0) { - if(Array.isArray(options.entry) || typeof options.entry === "string") { - options.entry = { - main: options.entry - }; - } - ensureObject(options, "entry"); - - var addTo = function addTo(name, entry) { - if(options.entry[name]) { - if(!Array.isArray(options.entry[name])) { - options.entry[name] = [options.entry[name]]; - } - options.entry[name].push(entry); - } else { - options.entry[name] = entry; - } - }; - argv._.forEach(function(content) { - var i = content.indexOf("="); - var j = content.indexOf("?"); - if(i < 0 || (j >= 0 && j < i)) { - var resolved = path.resolve(content); - if(fs.existsSync(resolved)) { - addTo("main", `${resolved}${fs.statSync(resolved).isDirectory() ? path.sep : ""}`); - } else { - addTo("main", content); - } - } else { - addTo(content.substr(0, i), content.substr(i + 1)); - } - }); - } - - if(!options.entry) { - if(configFileLoaded) { - console.error("Configuration file found but no entry configured."); - } else { - console.error("No configuration file found and no entry configured via CLI option."); - console.error("When using the CLI you need to provide at least two arguments: entry and output."); - console.error("A configuration file could be named 'webpack.config.js' in the current directory."); - } - console.error("Use --help to display the CLI options."); - process.exit(-1); // eslint-disable-line - } - } -}; diff --git a/node_modules/webpack/bin/webpack.js b/node_modules/webpack/bin/webpack.js index 469900c73..a72097491 100755 --- a/node_modules/webpack/bin/webpack.js +++ b/node_modules/webpack/bin/webpack.js @@ -1,398 +1,168 @@ #!/usr/bin/env node -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ -var path = require("path"); - -// Local version replace global one -try { - var localWebpack = require.resolve(path.join(process.cwd(), "node_modules", "webpack", "bin", "webpack.js")); - if(__filename !== localWebpack) { - return require(localWebpack); - } -} catch(e) {} -var yargs = require("yargs") - .usage("webpack " + require("../package.json").version + "\n" + - "Usage: https://webpack.js.org/api/cli/\n" + - "Usage without config file: webpack <entry> [<entry>] <output>\n" + - "Usage with config file: webpack"); - -require("./config-yargs")(yargs); +process.exitCode = 0; + +/** + * @param {string} command process to run + * @param {string[]} args commandline 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 + }); -var DISPLAY_GROUP = "Stats options:"; -var BASIC_GROUP = "Basic options:"; + executedCommand.on("error", error => { + reject(error); + }); -yargs.options({ - "json": { - type: "boolean", - alias: "j", - describe: "Prints the result as JSON." - }, - "progress": { - type: "boolean", - describe: "Print compilation progress in percentage", - group: BASIC_GROUP - }, - "color": { - type: "boolean", - alias: "colors", - default: function supportsColor() { - return require("supports-color"); - }, - group: DISPLAY_GROUP, - describe: "Enables/Disables colors on the console" - }, - "sort-modules-by": { - type: "string", - group: DISPLAY_GROUP, - describe: "Sorts the modules list by property in module" - }, - "sort-chunks-by": { - type: "string", - group: DISPLAY_GROUP, - describe: "Sorts the chunks list by property in chunk" - }, - "sort-assets-by": { - type: "string", - group: DISPLAY_GROUP, - describe: "Sorts the assets list by property in asset" - }, - "hide-modules": { - type: "boolean", - group: DISPLAY_GROUP, - describe: "Hides info about modules" - }, - "display-exclude": { - type: "string", - group: DISPLAY_GROUP, - describe: "Exclude modules in the output" - }, - "display-modules": { - type: "boolean", - group: DISPLAY_GROUP, - describe: "Display even excluded modules in the output" - }, - "display-max-modules": { - type: "number", - group: DISPLAY_GROUP, - describe: "Sets the maximum number of visible modules in output" - }, - "display-chunks": { - type: "boolean", - group: DISPLAY_GROUP, - describe: "Display chunks in the output" - }, - "display-entrypoints": { - type: "boolean", - group: DISPLAY_GROUP, - describe: "Display entry points in the output" - }, - "display-origins": { - type: "boolean", - group: DISPLAY_GROUP, - describe: "Display origins of chunks in the output" - }, - "display-cached": { - type: "boolean", - group: DISPLAY_GROUP, - describe: "Display also cached modules in the output" - }, - "display-cached-assets": { - type: "boolean", - group: DISPLAY_GROUP, - describe: "Display also cached assets in the output" - }, - "display-reasons": { - type: "boolean", - group: DISPLAY_GROUP, - describe: "Display reasons about module inclusion in the output" - }, - "display-depth": { - type: "boolean", - group: DISPLAY_GROUP, - describe: "Display distance from entry point for each module" - }, - "display-used-exports": { - type: "boolean", - group: DISPLAY_GROUP, - describe: "Display information about used exports in modules (Tree Shaking)" - }, - "display-provided-exports": { - type: "boolean", - group: DISPLAY_GROUP, - describe: "Display information about exports provided from modules" - }, - "display-optimization-bailout": { - type: "boolean", - group: DISPLAY_GROUP, - describe: "Display information about why optimization bailed out for modules" - }, - "display-error-details": { - type: "boolean", - group: DISPLAY_GROUP, - describe: "Display details about errors" - }, - "display": { - type: "string", - group: DISPLAY_GROUP, - describe: "Select display preset (verbose, detailed, normal, minimal, errors-only, none)" - }, - "verbose": { - type: "boolean", - group: DISPLAY_GROUP, - describe: "Show more details" + 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 => { + try { + require.resolve(packageName); + + return true; + } catch (err) { + return false; } -}); - -// yargs will terminate the process early when the user uses help or version. -// This causes large help outputs to be cut short (https://github.com/nodejs/node/wiki/API-changes-between-v0.10-and-v4#process). -// To prevent this we use the yargs.parse API and exit the process normally -yargs.parse(process.argv.slice(2), (err, argv, output) => { - - // arguments validation failed - if(err && output) { - console.error(output); - process.exitCode = 1; - return; +}; + +/** + * @typedef {Object} CliOption + * @property {string} name display name + * @property {string} package npm package name + * @property {string} binName name of the executable file + * @property {string} alias shortcut for choice + * @property {boolean} installed currently installed? + * @property {boolean} recommended is recommended + * @property {string} url homepage + * @property {string} description description + */ + +/** @type {CliOption[]} */ +const CLIs = [ + { + name: "webpack-cli", + package: "webpack-cli", + binName: "webpack-cli", + alias: "cli", + installed: isInstalled("webpack-cli"), + recommended: true, + url: "https://github.com/webpack/webpack-cli", + description: "The original webpack full-featured CLI." + }, + { + name: "webpack-command", + package: "webpack-command", + binName: "webpack-command", + alias: "command", + installed: isInstalled("webpack-command"), + recommended: false, + url: "https://github.com/webpack-contrib/webpack-command", + description: "A lightweight, opinionated webpack CLI." } +]; - // help or version info - if(output) { - console.log(output); - return; - } +const installedClis = CLIs.filter(cli => cli.installed); - if(argv.verbose) { - argv["display"] = "verbose"; - } +if (installedClis.length === 0) { + const path = require("path"); + const fs = require("fs"); + const readLine = require("readline"); - var options = require("./convert-argv")(yargs, argv); + let notify = + "One CLI for webpack must be installed. These are recommended choices, delivered as separate packages:"; - function ifArg(name, fn, init) { - if(Array.isArray(argv[name])) { - if(init) init(); - argv[name].forEach(fn); - } else if(typeof argv[name] !== "undefined") { - if(init) init(); - fn(argv[name], -1); + for (const item of CLIs) { + if (item.recommended) { + notify += `\n - ${item.name} (${item.url})\n ${item.description}`; } } - function processOptions(options) { - // process Promise - if(typeof options.then === "function") { - options.then(processOptions).catch(function(err) { - console.error(err.stack || err); - process.exit(1); // eslint-disable-line - }); - return; - } + console.error(notify); - var firstOptions = [].concat(options)[0]; - var statsPresetToOptions = require("../lib/Stats.js").presetToOptions; + const isYarn = fs.existsSync(path.resolve(process.cwd(), "yarn.lock")); - var outputOptions = options.stats; - if(typeof outputOptions === "boolean" || typeof outputOptions === "string") { - outputOptions = statsPresetToOptions(outputOptions); - } else if(!outputOptions) { - outputOptions = {}; - } + const packageManager = isYarn ? "yarn" : "npm"; + const installOptions = [isYarn ? "add" : "install", "-D"]; - ifArg("display", function(preset) { - outputOptions = statsPresetToOptions(preset); - }); + console.error( + `We will use "${packageManager}" to install the CLI via "${packageManager} ${installOptions.join( + " " + )}".` + ); - outputOptions = Object.create(outputOptions); - if(Array.isArray(options) && !outputOptions.children) { - outputOptions.children = options.map(o => o.stats); - } - if(typeof outputOptions.context === "undefined") - outputOptions.context = firstOptions.context; - - ifArg("env", function(value) { - if(outputOptions.env) { - outputOptions._env = value; - } - }); - - ifArg("json", function(bool) { - if(bool) - outputOptions.json = bool; - }); + let question = `Do you want to install 'webpack-cli' (yes/no): `; - if(typeof outputOptions.colors === "undefined") - outputOptions.colors = require("supports-color"); + const questionInterface = readLine.createInterface({ + input: process.stdin, + output: process.stderr + }); + questionInterface.question(question, answer => { + questionInterface.close(); - ifArg("sort-modules-by", function(value) { - outputOptions.modulesSort = value; - }); - - ifArg("sort-chunks-by", function(value) { - outputOptions.chunksSort = value; - }); + const normalizedAnswer = answer.toLowerCase().startsWith("y"); - ifArg("sort-assets-by", function(value) { - outputOptions.assetsSort = value; - }); - - ifArg("display-exclude", function(value) { - outputOptions.exclude = value; - }); + if (!normalizedAnswer) { + console.error( + "You need to install 'webpack-cli' to use webpack via CLI.\n" + + "You can also install the CLI manually." + ); + process.exitCode = 1; - if(!outputOptions.json) { - if(typeof outputOptions.cached === "undefined") - outputOptions.cached = false; - if(typeof outputOptions.cachedAssets === "undefined") - outputOptions.cachedAssets = false; - - ifArg("display-chunks", function(bool) { - if(bool) { - outputOptions.modules = false; - outputOptions.chunks = true; - outputOptions.chunkModules = true; - } - }); - - ifArg("display-entrypoints", function(bool) { - if(bool) - outputOptions.entrypoints = true; - }); - - ifArg("display-reasons", function(bool) { - if(bool) - outputOptions.reasons = true; - }); - - ifArg("display-depth", function(bool) { - if(bool) - outputOptions.depth = true; - }); - - ifArg("display-used-exports", function(bool) { - if(bool) - outputOptions.usedExports = true; - }); - - ifArg("display-provided-exports", function(bool) { - if(bool) - outputOptions.providedExports = true; - }); - - ifArg("display-optimization-bailout", function(bool) { - if(bool) - outputOptions.optimizationBailout = bool; - }); - - ifArg("display-error-details", function(bool) { - if(bool) - outputOptions.errorDetails = true; - }); - - ifArg("display-origins", function(bool) { - if(bool) - outputOptions.chunkOrigins = true; - }); - - ifArg("display-max-modules", function(value) { - outputOptions.maxModules = +value; - }); - - ifArg("display-cached", function(bool) { - if(bool) - outputOptions.cached = true; - }); - - ifArg("display-cached-assets", function(bool) { - if(bool) - outputOptions.cachedAssets = true; - }); - - if(!outputOptions.exclude) - outputOptions.exclude = ["node_modules", "bower_components", "components"]; - - if(argv["display-modules"]) { - outputOptions.maxModules = Infinity; - outputOptions.exclude = undefined; - outputOptions.modules = true; - } - } - - ifArg("hide-modules", function(bool) { - if(bool) { - outputOptions.modules = false; - outputOptions.chunkModules = false; - } - }); - - var webpack = require("../lib/webpack.js"); - - Error.stackTraceLimit = 30; - var lastHash = null; - var compiler; - try { - compiler = webpack(options); - } catch(err) { - if(err.name === "WebpackOptionsValidationError") { - if(argv.color) - console.error( - `\u001b[1m\u001b[31m${err.message}\u001b[39m\u001b[22m` - ); - else - console.error(err.message); - // eslint-disable-next-line no-process-exit - process.exit(1); - } - - throw err; - } - - if(argv.progress) { - var ProgressPlugin = require("../lib/ProgressPlugin"); - compiler.apply(new ProgressPlugin({ - profile: argv.profile - })); - } - - function compilerCallback(err, stats) { - if(!options.watch || err) { - // Do not keep cache anymore - compiler.purgeInputFileSystem(); - } - if(err) { - lastHash = null; - console.error(err.stack || err); - if(err.details) console.error(err.details); - process.exit(1); // eslint-disable-line - } - if(outputOptions.json) { - process.stdout.write(JSON.stringify(stats.toJson(outputOptions), null, 2) + "\n"); - } else if(stats.hash !== lastHash) { - lastHash = stats.hash; - var statsString = stats.toString(outputOptions); - if(statsString) - process.stdout.write(statsString + "\n"); - } - if(!options.watch && stats.hasErrors()) { - process.exitCode = 2; - } + return; } - if(firstOptions.watch || options.watch) { - var watchOptions = firstOptions.watchOptions || firstOptions.watch || options.watch || {}; - if(watchOptions.stdin) { - process.stdin.on("end", function() { - process.exit(); // eslint-disable-line - }); - process.stdin.resume(); - } - compiler.watch(watchOptions, compilerCallback); - console.log("\nWebpack is watching the files…\n"); - } else - compiler.run(compilerCallback); - - } - - processOptions(options); -}); + const packageName = "webpack-cli"; + + console.log( + `Installing '${packageName}' (running '${packageManager} ${installOptions.join( + " " + )} ${packageName}')...` + ); + + runCommand(packageManager, installOptions.concat(packageName)) + .then(() => { + require(packageName); //eslint-disable-line + }) + .catch(error => { + console.error(error); + process.exitCode = 1; + }); + }); +} else if (installedClis.length === 1) { + const path = require("path"); + const pkgPath = require.resolve(`${installedClis[0].package}/package.json`); + // eslint-disable-next-line node/no-missing-require + const pkg = require(pkgPath); + // eslint-disable-next-line node/no-missing-require + require(path.resolve( + path.dirname(pkgPath), + pkg.bin[installedClis[0].binName] + )); +} else { + console.warn( + `You have installed ${installedClis + .map(item => item.name) + .join( + " and " + )} together. To work with the "webpack" command you need only one CLI package, please remove one of them or use them directly via their binary.` + ); + process.exitCode = 1; +} diff --git a/node_modules/webpack/buildin/.eslintrc b/node_modules/webpack/buildin/.eslintrc deleted file mode 100644 index 7638d61e6..000000000 --- a/node_modules/webpack/buildin/.eslintrc +++ /dev/null @@ -1,7 +0,0 @@ -{
- "env": {
- "node": true,
- "es6": false,
- "browser": true
- }
-}
diff --git a/node_modules/webpack/buildin/amd-define.js b/node_modules/webpack/buildin/amd-define.js index 006df1756..0d32606a1 100644 --- a/node_modules/webpack/buildin/amd-define.js +++ b/node_modules/webpack/buildin/amd-define.js @@ -1,3 +1,3 @@ -module.exports = function() {
- throw new Error("define cannot be used indirect");
-};
+module.exports = function() { + throw new Error("define cannot be used indirect"); +}; diff --git a/node_modules/webpack/buildin/amd-options.js b/node_modules/webpack/buildin/amd-options.js index 72600c4d2..f7dd47533 100644 --- a/node_modules/webpack/buildin/amd-options.js +++ b/node_modules/webpack/buildin/amd-options.js @@ -1,2 +1,2 @@ -/* globals __webpack_amd_options__ */
-module.exports = __webpack_amd_options__;
+/* globals __webpack_amd_options__ */ +module.exports = __webpack_amd_options__; diff --git a/node_modules/webpack/buildin/global.js b/node_modules/webpack/buildin/global.js index b025ee7f6..35f3144e9 100644 --- a/node_modules/webpack/buildin/global.js +++ b/node_modules/webpack/buildin/global.js @@ -1,21 +1,20 @@ -var g;
-
-// This works in non-strict mode
-g = (function() {
- return this;
-})();
-
-try {
- // This works if eval is allowed (see CSP)
- g = g || Function("return this")() || (1,eval)("this");
-} catch(e) {
- // This works if the window reference is available
- if(typeof window === "object")
- g = window;
-}
-
-// g can still be undefined, but nothing to do about it...
-// We return undefined, instead of nothing here, so it's
-// easier to handle this case. if(!global) { ...}
-
-module.exports = g;
+var g; + +// This works in non-strict mode +g = (function() { + return this; +})(); + +try { + // This works if eval is allowed (see CSP) + g = g || Function("return this")() || (1, eval)("this"); +} catch (e) { + // This works if the window reference is available + if (typeof window === "object") g = window; +} + +// g can still be undefined, but nothing to do about it... +// We return undefined, instead of nothing here, so it's +// easier to handle this case. if(!global) { ...} + +module.exports = g; diff --git a/node_modules/webpack/buildin/harmony-module.js b/node_modules/webpack/buildin/harmony-module.js index 0a3c5d175..c16146586 100644 --- a/node_modules/webpack/buildin/harmony-module.js +++ b/node_modules/webpack/buildin/harmony-module.js @@ -1,24 +1,24 @@ -module.exports = function(originalModule) {
- if(!originalModule.webpackPolyfill) {
- var module = Object.create(originalModule);
- // module.parent = undefined by default
- if(!module.children) module.children = [];
- Object.defineProperty(module, "loaded", {
- enumerable: true,
- get: function() {
- return module.l;
- }
- });
- Object.defineProperty(module, "id", {
- enumerable: true,
- get: function() {
- return module.i;
- }
- });
- Object.defineProperty(module, "exports", {
- enumerable: true,
- });
- module.webpackPolyfill = 1;
- }
- return module;
-};
+module.exports = function(originalModule) { + if (!originalModule.webpackPolyfill) { + var module = Object.create(originalModule); + // module.parent = undefined by default + if (!module.children) module.children = []; + Object.defineProperty(module, "loaded", { + enumerable: true, + get: function() { + return module.l; + } + }); + Object.defineProperty(module, "id", { + enumerable: true, + get: function() { + return module.i; + } + }); + Object.defineProperty(module, "exports", { + enumerable: true + }); + module.webpackPolyfill = 1; + } + return module; +}; diff --git a/node_modules/webpack/buildin/module.js b/node_modules/webpack/buildin/module.js index 52f02a735..c92808b60 100644 --- a/node_modules/webpack/buildin/module.js +++ b/node_modules/webpack/buildin/module.js @@ -1,22 +1,22 @@ -module.exports = function(module) {
- if(!module.webpackPolyfill) {
- module.deprecate = function() {};
- module.paths = [];
- // module.parent = undefined by default
- if(!module.children) module.children = [];
- Object.defineProperty(module, "loaded", {
- enumerable: true,
- get: function() {
- return module.l;
- }
- });
- Object.defineProperty(module, "id", {
- enumerable: true,
- get: function() {
- return module.i;
- }
- });
- module.webpackPolyfill = 1;
- }
- return module;
-};
+module.exports = function(module) { + if (!module.webpackPolyfill) { + module.deprecate = function() {}; + module.paths = []; + // module.parent = undefined by default + if (!module.children) module.children = []; + Object.defineProperty(module, "loaded", { + enumerable: true, + get: function() { + return module.l; + } + }); + Object.defineProperty(module, "id", { + enumerable: true, + get: function() { + return module.i; + } + }); + module.webpackPolyfill = 1; + } + return module; +}; diff --git a/node_modules/webpack/buildin/system.js b/node_modules/webpack/buildin/system.js index 8dac967a2..9ba70a384 100644 --- a/node_modules/webpack/buildin/system.js +++ b/node_modules/webpack/buildin/system.js @@ -1,7 +1,7 @@ -// Provide a "System" global.
-module.exports = {
- // Make sure import is only used as "System.import"
- import: function() {
- throw new Error("System.import cannot be used indirectly");
- }
-};
+// Provide a "System" global. +module.exports = { + // Make sure import is only used as "System.import" + import: function() { + throw new Error("System.import cannot be used indirectly"); + } +}; diff --git a/node_modules/webpack/hot/.eslintrc b/node_modules/webpack/hot/.eslintrc deleted file mode 100644 index cceb1047b..000000000 --- a/node_modules/webpack/hot/.eslintrc +++ /dev/null @@ -1,9 +0,0 @@ -{
- "env": {
- "node": true
- },
- "rules": {
- "node/exports-style": ["off"]
- }
-
-}
diff --git a/node_modules/webpack/hot/dev-server.js b/node_modules/webpack/hot/dev-server.js index 95894674d..682a47f84 100644 --- a/node_modules/webpack/hot/dev-server.js +++ b/node_modules/webpack/hot/dev-server.js @@ -1,53 +1,61 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-/*globals window __webpack_hash__ */
-if(module.hot) {
- var lastHash;
- var upToDate = function upToDate() {
- return 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. Need to do a full reload!");
- log("warning", "[HMR] (Probably because of restarting the webpack-dev-server)");
- 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. Need to do a full reload!");
- log("warning", "[HMR] " + err.stack || err.message);
- window.location.reload();
- } else {
- log("warning", "[HMR] Update failed: " + err.stack || err.message);
- }
- });
- };
- 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.");
-}
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +/*globals window __webpack_hash__ */ +if (module.hot) { + var lastHash; + var upToDate = function upToDate() { + return 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. Need to do a full reload!"); + log( + "warning", + "[HMR] (Probably because of restarting the webpack-dev-server)" + ); + 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. Need to do a full reload!" + ); + log("warning", "[HMR] " + (err.stack || err.message)); + window.location.reload(); + } else { + log("warning", "[HMR] Update failed: " + (err.stack || err.message)); + } + }); + }; + 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."); +} diff --git a/node_modules/webpack/hot/emitter.js b/node_modules/webpack/hot/emitter.js index 0c26a031e..05e0fbe09 100644 --- a/node_modules/webpack/hot/emitter.js +++ b/node_modules/webpack/hot/emitter.js @@ -1,2 +1,2 @@ -var EventEmitter = require("events");
-module.exports = new EventEmitter();
+var EventEmitter = require("events"); +module.exports = new EventEmitter(); diff --git a/node_modules/webpack/hot/log-apply-result.js b/node_modules/webpack/hot/log-apply-result.js index 8a312b3c6..b63e75741 100644 --- a/node_modules/webpack/hot/log-apply-result.js +++ b/node_modules/webpack/hot/log-apply-result.js @@ -1,38 +1,44 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-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 NamedModulesPlugin for module names.");
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +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 NamedModulesPlugin for module names." + ); + } +}; diff --git a/node_modules/webpack/hot/log.js b/node_modules/webpack/hot/log.js index 2ade0511d..0d05673f8 100644 --- a/node_modules/webpack/hot/log.js +++ b/node_modules/webpack/hot/log.js @@ -1,44 +1,47 @@ -var logLevel = "info";
-
-function dummy() {}
-
-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;
-}
-
-function logGroup(logFn) {
- return function(level, msg) {
- if(shouldLog(level)) {
- logFn(msg);
- }
- };
-}
-
-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);
-
-module.exports.setLogLevel = function(level) {
- logLevel = level;
-};
+var logLevel = "info"; + +function dummy() {} + +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; +} + +function logGroup(logFn) { + return function(level, msg) { + if (shouldLog(level)) { + logFn(msg); + } + }; +} + +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); + } + } +}; + +/* eslint-disable node/no-unsupported-features/node-builtins */ +var group = console.group || dummy; +var groupCollapsed = console.groupCollapsed || dummy; +var groupEnd = console.groupEnd || dummy; +/* eslint-enable node/no-unsupported-features/node-builtins */ + +module.exports.group = logGroup(group); + +module.exports.groupCollapsed = logGroup(groupCollapsed); + +module.exports.groupEnd = logGroup(groupEnd); + +module.exports.setLogLevel = function(level) { + logLevel = level; +}; diff --git a/node_modules/webpack/hot/only-dev-server.js b/node_modules/webpack/hot/only-dev-server.js index 252df58fd..043f2430b 100644 --- a/node_modules/webpack/hot/only-dev-server.js +++ b/node_modules/webpack/hot/only-dev-server.js @@ -1,71 +1,105 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-/*globals __webpack_hash__ */
-if(module.hot) {
- var lastHash;
- var upToDate = function upToDate() {
- return 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] " + err.stack || err.message);
- } else {
- log("warning", "[HMR] Update check failed: " + err.stack || err.message);
- }
- });
- };
- 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.");
-}
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +/*globals __webpack_hash__ */ +if (module.hot) { + var lastHash; + var upToDate = function upToDate() { + return 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] " + (err.stack || err.message)); + } else { + log( + "warning", + "[HMR] Update check failed: " + (err.stack || err.message) + ); + } + }); + }; + 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."); +} diff --git a/node_modules/webpack/hot/poll.js b/node_modules/webpack/hot/poll.js index 75e3a2b67..8193db01f 100644 --- a/node_modules/webpack/hot/poll.js +++ b/node_modules/webpack/hot/poll.js @@ -1,34 +1,40 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-/*globals __resourceQuery */
-if(module.hot) {
- var hotPollInterval = +(__resourceQuery.substr(1)) || (10 * 60 * 1000);
- var log = require("./log");
-
- 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] " + err.stack || err.message);
- log("warning", "[HMR] You need to restart the application!");
- } else {
- log("warning", "[HMR] Update failed: " + err.stack || err.message);
- }
- });
- }
- };
- setInterval(checkForUpdate, hotPollInterval);
-} else {
- throw new Error("[HMR] Hot Module Replacement is disabled.");
-}
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +/*globals __resourceQuery */ +if (module.hot) { + var hotPollInterval = +__resourceQuery.substr(1) || 10 * 60 * 1000; + var log = require("./log"); + + 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] " + (err.stack || err.message)); + log("warning", "[HMR] You need to restart the application!"); + } else { + log( + "warning", + "[HMR] Update failed: " + (err.stack || err.message) + ); + } + }); + } + }; + setInterval(checkForUpdate, hotPollInterval); +} else { + throw new Error("[HMR] Hot Module Replacement is disabled."); +} diff --git a/node_modules/webpack/hot/signal.js b/node_modules/webpack/hot/signal.js index 77ec94d4a..24c4f5cb3 100644 --- a/node_modules/webpack/hot/signal.js +++ b/node_modules/webpack/hot/signal.js @@ -1,51 +1,62 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-/*globals __resourceQuery */
-if(module.hot) {
- var log = require("./log");
- 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);
- });
- }).catch(function(err) {
- var status = module.hot.status();
- if(["abort", "fail"].indexOf(status) >= 0) {
- log("warning", "[HMR] Cannot apply update.");
- log("warning", "[HMR] " + err.stack || err.message);
- log("warning", "[HMR] You need to restart the application!");
- } else {
- log("warning", "[HMR] Update failed: " + err.stack || err.message);
- }
- });
- };
-
- process.on(__resourceQuery.substr(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.");
-}
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +/*globals __resourceQuery */ +if (module.hot) { + var log = require("./log"); + 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] " + (err.stack || err.message)); + log("warning", "[HMR] You need to restart the application!"); + } else { + log("warning", "[HMR] Update failed: " + (err.stack || err.message)); + } + }); + }; + + process.on(__resourceQuery.substr(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."); +} diff --git a/node_modules/webpack/lib/APIPlugin.js b/node_modules/webpack/lib/APIPlugin.js index 19a5be424..6cd80646d 100644 --- a/node_modules/webpack/lib/APIPlugin.js +++ b/node_modules/webpack/lib/APIPlugin.js @@ -1,45 +1,84 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const ConstDependency = require("./dependencies/ConstDependency");
-const ParserHelpers = require("./ParserHelpers");
-
-const NullFactory = require("./NullFactory");
-
-const REPLACEMENTS = {
- __webpack_require__: "__webpack_require__", // eslint-disable-line camelcase
- __webpack_public_path__: "__webpack_require__.p", // eslint-disable-line camelcase
- __webpack_modules__: "__webpack_require__.m", // eslint-disable-line camelcase
- __webpack_chunk_load__: "__webpack_require__.e", // eslint-disable-line camelcase
- __non_webpack_require__: "require", // eslint-disable-line camelcase
- __webpack_nonce__: "__webpack_require__.nc", // eslint-disable-line camelcase
- "require.onError": "__webpack_require__.oe" // eslint-disable-line camelcase
-};
-const REPLACEMENT_TYPES = {
- __webpack_public_path__: "string", // eslint-disable-line camelcase
- __webpack_require__: "function", // eslint-disable-line camelcase
- __webpack_modules__: "object", // eslint-disable-line camelcase
- __webpack_chunk_load__: "function", // eslint-disable-line camelcase
- __webpack_nonce__: "string" // eslint-disable-line camelcase
-};
-
-class APIPlugin {
- apply(compiler) {
- compiler.plugin("compilation", (compilation, params) => {
- compilation.dependencyFactories.set(ConstDependency, new NullFactory());
- compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
-
- params.normalModuleFactory.plugin("parser", parser => {
- Object.keys(REPLACEMENTS).forEach(key => {
- parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
- parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
- });
- });
- });
- }
-}
-
-module.exports = APIPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const ConstDependency = require("./dependencies/ConstDependency"); +const ParserHelpers = require("./ParserHelpers"); + +const NullFactory = require("./NullFactory"); + +/* eslint-disable camelcase */ +const REPLACEMENTS = { + __webpack_require__: "__webpack_require__", + __webpack_public_path__: "__webpack_require__.p", + __webpack_modules__: "__webpack_require__.m", + __webpack_chunk_load__: "__webpack_require__.e", + __non_webpack_require__: "require", + __webpack_nonce__: "__webpack_require__.nc", + "require.onError": "__webpack_require__.oe" +}; +const NO_WEBPACK_REQUIRE = { + __non_webpack_require__: true +}; +const REPLACEMENT_TYPES = { + __webpack_public_path__: "string", + __webpack_require__: "function", + __webpack_modules__: "object", + __webpack_chunk_load__: "function", + __webpack_nonce__: "string" +}; +/* eslint-enable camelcase */ + +class APIPlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "APIPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set(ConstDependency, new NullFactory()); + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); + + const handler = parser => { + Object.keys(REPLACEMENTS).forEach(key => { + parser.hooks.expression + .for(key) + .tap( + "APIPlugin", + NO_WEBPACK_REQUIRE[key] + ? ParserHelpers.toConstantDependency( + parser, + REPLACEMENTS[key] + ) + : ParserHelpers.toConstantDependencyWithWebpackRequire( + parser, + REPLACEMENTS[key] + ) + ); + parser.hooks.evaluateTypeof + .for(key) + .tap( + "APIPlugin", + ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]) + ); + }); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("APIPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("APIPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("APIPlugin", handler); + } + ); + } +} + +module.exports = APIPlugin; diff --git a/node_modules/webpack/lib/AmdMainTemplatePlugin.js b/node_modules/webpack/lib/AmdMainTemplatePlugin.js index 727f49ba3..ff715ec6c 100644 --- a/node_modules/webpack/lib/AmdMainTemplatePlugin.js +++ b/node_modules/webpack/lib/AmdMainTemplatePlugin.js @@ -1,56 +1,87 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
- */
-
-"use strict";
-
-const ConcatSource = require("webpack-sources").ConcatSource;
-const Template = require("./Template");
-
-class AmdMainTemplatePlugin {
- constructor(name) {
- this.name = name;
- }
-
- apply(compilation) {
- const mainTemplate = compilation.mainTemplate;
-
- compilation.templatesPlugin("render-with-entry", (source, chunk, hash) => {
- const externals = chunk.getModules().filter((m) => m.external);
- const externalsDepsArray = JSON.stringify(externals.map((m) =>
- typeof m.request === "object" ? m.request.amd : m.request
- ));
- const externalsArguments = externals.map((m) =>
- Template.toIdentifier(`__WEBPACK_EXTERNAL_MODULE_${m.id}__`)
- ).join(", ");
-
- if(this.name) {
- const name = mainTemplate.applyPluginsWaterfall("asset-path", this.name, {
- hash,
- chunk
- });
-
- return new ConcatSource(
- `define(${JSON.stringify(name)}, ${externalsDepsArray}, function(${externalsArguments}) { return `, source, "});"
- );
- } else if(externalsArguments) {
- return new ConcatSource(`define(${externalsDepsArray}, function(${externalsArguments}) { return `, source, "});");
- } else {
- return new ConcatSource("define(function() { return ", source, "});");
- }
- });
-
- mainTemplate.plugin("global-hash-paths", (paths) => {
- if(this.name) paths.push(this.name);
- return paths;
- });
-
- mainTemplate.plugin("hash", (hash) => {
- hash.update("exports amd");
- hash.update(this.name);
- });
- }
-}
-
-module.exports = AmdMainTemplatePlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra + */ + +"use strict"; + +const { ConcatSource } = require("webpack-sources"); +const Template = require("./Template"); + +/** @typedef {import("./Compilation")} Compilation */ + +class AmdMainTemplatePlugin { + /** + * @param {string} name the library name + */ + constructor(name) { + /** @type {string} */ + this.name = name; + } + + /** + * @param {Compilation} compilation the compilation instance + * @returns {void} + */ + apply(compilation) { + const { mainTemplate, chunkTemplate } = compilation; + + const onRenderWithEntry = (source, chunk, hash) => { + const externals = chunk.getModules().filter(m => m.external); + const externalsDepsArray = JSON.stringify( + externals.map( + m => (typeof m.request === "object" ? m.request.amd : m.request) + ) + ); + const externalsArguments = externals + .map( + m => `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier(`${m.id}`)}__` + ) + .join(", "); + + if (this.name) { + const name = mainTemplate.getAssetPath(this.name, { + hash, + chunk + }); + + return new ConcatSource( + `define(${JSON.stringify( + name + )}, ${externalsDepsArray}, function(${externalsArguments}) { return `, + source, + "});" + ); + } else if (externalsArguments) { + return new ConcatSource( + `define(${externalsDepsArray}, function(${externalsArguments}) { return `, + source, + "});" + ); + } else { + return new ConcatSource("define(function() { return ", source, "});"); + } + }; + + for (const template of [mainTemplate, chunkTemplate]) { + template.hooks.renderWithEntry.tap( + "AmdMainTemplatePlugin", + onRenderWithEntry + ); + } + + mainTemplate.hooks.globalHashPaths.tap("AmdMainTemplatePlugin", paths => { + if (this.name) { + paths.push(this.name); + } + return paths; + }); + + mainTemplate.hooks.hash.tap("AmdMainTemplatePlugin", hash => { + hash.update("exports amd"); + hash.update(this.name); + }); + } +} + +module.exports = AmdMainTemplatePlugin; diff --git a/node_modules/webpack/lib/AsyncDependenciesBlock.js b/node_modules/webpack/lib/AsyncDependenciesBlock.js index 27d5988b6..a7e029131 100644 --- a/node_modules/webpack/lib/AsyncDependenciesBlock.js +++ b/node_modules/webpack/lib/AsyncDependenciesBlock.js @@ -1,43 +1,110 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const DependenciesBlock = require("./DependenciesBlock");
-
-module.exports = class AsyncDependenciesBlock extends DependenciesBlock {
- constructor(name, module, loc) {
- super();
- this.chunkName = name;
- this.chunks = null;
- this.module = module;
- this.loc = loc;
- }
- get chunk() {
- throw new Error("`chunk` was been renamed to `chunks` and is now an array");
- }
- set chunk(chunk) {
- throw new Error("`chunk` was been renamed to `chunks` and is now an array");
- }
- updateHash(hash) {
- hash.update(this.chunkName || "");
- hash.update(this.chunks && this.chunks.map((chunk) => {
- return chunk.id !== null ? chunk.id : "";
- }).join(",") || "");
- super.updateHash(hash);
- }
- disconnect() {
- this.chunks = null;
- super.disconnect();
- }
- unseal() {
- this.chunks = null;
- super.unseal();
- }
- sortItems() {
- super.sortItems();
- if(this.chunks) {
- this.chunks.sort((a, b) => a.compareTo(b));
- }
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const DependenciesBlock = require("./DependenciesBlock"); + +/** @typedef {import("./ChunkGroup")} ChunkGroup */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./util/createHash").Hash} Hash */ +/** @typedef {TODO} GroupOptions */ + +module.exports = class AsyncDependenciesBlock extends DependenciesBlock { + /** + * @param {GroupOptions} groupOptions options for the group + * @param {Module} module the Module object + * @param {DependencyLocation=} loc the line of code + * @param {TODO=} request the request + */ + constructor(groupOptions, module, loc, request) { + super(); + if (typeof groupOptions === "string") { + groupOptions = { name: groupOptions }; + } else if (!groupOptions) { + groupOptions = { name: undefined }; + } + this.groupOptions = groupOptions; + /** @type {ChunkGroup=} */ + this.chunkGroup = undefined; + this.module = module; + this.loc = loc; + this.request = request; + /** @type {DependenciesBlock} */ + this.parent = undefined; + } + + /** + * @returns {string} The name of the chunk + */ + get chunkName() { + return this.groupOptions.name; + } + + /** + * @param {string} value The new chunk name + * @returns {void} + */ + set chunkName(value) { + this.groupOptions.name = value; + } + + /** + * @returns {never} this throws and should never be called + */ + get chunks() { + throw new Error("Moved to AsyncDependenciesBlock.chunkGroup"); + } + + /** + * @param {never} value setter value + * @returns {never} this is going to throw therefore we should throw type + * assertions by returning never + */ + set chunks(value) { + throw new Error("Moved to AsyncDependenciesBlock.chunkGroup"); + } + + /** + * @param {Hash} hash the hash used to track block changes, from "crypto" module + * @returns {void} + */ + updateHash(hash) { + hash.update(JSON.stringify(this.groupOptions)); + hash.update( + (this.chunkGroup && + this.chunkGroup.chunks + .map(chunk => { + return chunk.id !== null ? chunk.id : ""; + }) + .join(",")) || + "" + ); + super.updateHash(hash); + } + + /** + * @returns {void} + */ + disconnect() { + this.chunkGroup = undefined; + super.disconnect(); + } + + /** + * @returns {void} + */ + unseal() { + this.chunkGroup = undefined; + super.unseal(); + } + + /** + * @returns {void} + */ + sortItems() { + super.sortItems(); + } +}; diff --git a/node_modules/webpack/lib/AsyncDependencyToInitialChunkWarning.js b/node_modules/webpack/lib/AsyncDependencyToInitialChunkWarning.js deleted file mode 100644 index b917b4f60..000000000 --- a/node_modules/webpack/lib/AsyncDependencyToInitialChunkWarning.js +++ /dev/null @@ -1,21 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Sean Larkin @thelarkinn
-*/
-"use strict";
-
-const WebpackError = require("./WebpackError");
-
-module.exports = class AsyncDependencyToInitialChunkWarning extends WebpackError {
- constructor(chunkName, module, loc) {
- super();
-
- this.name = "AsyncDependencyToInitialChunkWarning";
- this.message = `It's not allowed to load an initial chunk on demand. The chunk name "${chunkName}" is already used by an entrypoint.`;
- this.module = module;
- this.origin = module;
- this.originLoc = loc;
-
- Error.captureStackTrace(this, this.constructor);
- }
-};
diff --git a/node_modules/webpack/lib/AutomaticPrefetchPlugin.js b/node_modules/webpack/lib/AutomaticPrefetchPlugin.js index 8652d1cc8..2d0db16ec 100644 --- a/node_modules/webpack/lib/AutomaticPrefetchPlugin.js +++ b/node_modules/webpack/lib/AutomaticPrefetchPlugin.js @@ -1,36 +1,57 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const asyncLib = require("async");
-const PrefetchDependency = require("./dependencies/PrefetchDependency");
-const NormalModule = require("./NormalModule");
-
-class AutomaticPrefetchPlugin {
- apply(compiler) {
- compiler.plugin("compilation", (compilation, params) => {
- const normalModuleFactory = params.normalModuleFactory;
-
- compilation.dependencyFactories.set(PrefetchDependency, normalModuleFactory);
- });
- let lastModules = null;
- compiler.plugin("after-compile", (compilation, callback) => {
- lastModules = compilation.modules
- .filter(m => m instanceof NormalModule)
- .map(m => ({
- context: m.context,
- request: m.request
- }));
- callback();
- });
- compiler.plugin("make", (compilation, callback) => {
- if(!lastModules) return callback();
- asyncLib.forEach(lastModules, (m, callback) => {
- compilation.prefetch(m.context || compiler.context, new PrefetchDependency(m.request), callback);
- }, callback);
- });
- }
-}
-module.exports = AutomaticPrefetchPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const asyncLib = require("neo-async"); +const PrefetchDependency = require("./dependencies/PrefetchDependency"); +const NormalModule = require("./NormalModule"); + +/** @typedef {import("./Compiler")} Compiler */ + +class AutomaticPrefetchPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler Webpack Compiler + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "AutomaticPrefetchPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + PrefetchDependency, + normalModuleFactory + ); + } + ); + let lastModules = null; + compiler.hooks.afterCompile.tap("AutomaticPrefetchPlugin", compilation => { + lastModules = compilation.modules + .filter(m => m instanceof NormalModule) + .map((/** @type {NormalModule} */ m) => ({ + context: m.context, + request: m.request + })); + }); + compiler.hooks.make.tapAsync( + "AutomaticPrefetchPlugin", + (compilation, callback) => { + if (!lastModules) return callback(); + asyncLib.forEach( + lastModules, + (m, callback) => { + compilation.prefetch( + m.context || compiler.context, + new PrefetchDependency(m.request), + callback + ); + }, + callback + ); + } + ); + } +} +module.exports = AutomaticPrefetchPlugin; diff --git a/node_modules/webpack/lib/BannerPlugin.js b/node_modules/webpack/lib/BannerPlugin.js index 342a30328..1e9aa343c 100644 --- a/node_modules/webpack/lib/BannerPlugin.js +++ b/node_modules/webpack/lib/BannerPlugin.js @@ -1,73 +1,117 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
- */
-
-"use strict";
-
-const ConcatSource = require("webpack-sources").ConcatSource;
-const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
-
-const wrapComment = (str) => {
- if(!str.includes("\n")) return `/*! ${str} */`;
- return `/*!\n * ${str.split("\n").join("\n * ")}\n */`;
-};
-
-class BannerPlugin {
- constructor(options) {
- if(arguments.length > 1)
- throw new Error("BannerPlugin only takes one argument (pass an options object)");
- if(typeof options === "string")
- options = {
- banner: options
- };
- this.options = options || {};
- this.banner = this.options.raw ? options.banner : wrapComment(options.banner);
- }
-
- apply(compiler) {
- const options = this.options;
- const banner = this.banner;
-
- compiler.plugin("compilation", (compilation) => {
- compilation.plugin("optimize-chunk-assets", (chunks, callback) => {
- chunks.forEach((chunk) => {
- if(options.entryOnly && !chunk.isInitial()) return;
- chunk.files
- .filter(ModuleFilenameHelpers.matchObject.bind(undefined, options))
- .forEach((file) => {
- let basename;
- let query = "";
- let filename = file;
- const hash = compilation.hash;
- const querySplit = filename.indexOf("?");
-
- if(querySplit >= 0) {
- query = filename.substr(querySplit);
- filename = filename.substr(0, querySplit);
- }
-
- if(filename.indexOf("/") < 0) {
- basename = filename;
- } else {
- basename = filename.substr(filename.lastIndexOf("/") + 1);
- }
-
- const comment = compilation.getPath(banner, {
- hash,
- chunk,
- filename,
- basename,
- query,
- });
-
- return compilation.assets[file] = new ConcatSource(comment, "\n", compilation.assets[file]);
- });
- });
- callback();
- });
- });
- }
-}
-
-module.exports = BannerPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra + */ + +"use strict"; + +const { ConcatSource } = require("webpack-sources"); +const ModuleFilenameHelpers = require("./ModuleFilenameHelpers"); +const Template = require("./Template"); + +const validateOptions = require("schema-utils"); +const schema = require("../schemas/plugins/BannerPlugin.json"); + +const wrapComment = str => { + if (!str.includes("\n")) { + return Template.toComment(str); + } + return `/*!\n * ${str + .replace(/\*\//g, "* /") + .split("\n") + .join("\n * ")}\n */`; +}; + +class BannerPlugin { + constructor(options) { + if (arguments.length > 1) { + throw new Error( + "BannerPlugin only takes one argument (pass an options object)" + ); + } + + validateOptions(schema, options, "Banner Plugin"); + + if (typeof options === "string" || typeof options === "function") { + options = { + banner: options + }; + } + + this.options = options || {}; + + if (typeof options.banner === "function") { + const getBanner = this.options.banner; + this.banner = this.options.raw + ? getBanner + : data => wrapComment(getBanner(data)); + } else { + const banner = this.options.raw + ? this.options.banner + : wrapComment(this.options.banner); + this.banner = () => banner; + } + } + + apply(compiler) { + const options = this.options; + const banner = this.banner; + const matchObject = ModuleFilenameHelpers.matchObject.bind( + undefined, + options + ); + + compiler.hooks.compilation.tap("BannerPlugin", compilation => { + compilation.hooks.optimizeChunkAssets.tap("BannerPlugin", chunks => { + for (const chunk of chunks) { + if (options.entryOnly && !chunk.canBeInitial()) { + continue; + } + + for (const file of chunk.files) { + if (!matchObject(file)) { + continue; + } + + let basename; + let query = ""; + let filename = file; + const hash = compilation.hash; + const querySplit = filename.indexOf("?"); + + if (querySplit >= 0) { + query = filename.substr(querySplit); + filename = filename.substr(0, querySplit); + } + + const lastSlashIndex = filename.lastIndexOf("/"); + + if (lastSlashIndex === -1) { + basename = filename; + } else { + basename = filename.substr(lastSlashIndex + 1); + } + + const data = { + hash, + chunk, + filename, + basename, + query + }; + + const comment = compilation.getPath(banner(data), data); + + compilation.assets[file] = new ConcatSource( + comment, + "\n", + compilation.assets[file] + ); + } + } + }); + }); + } +} + +module.exports = BannerPlugin; diff --git a/node_modules/webpack/lib/BasicEvaluatedExpression.js b/node_modules/webpack/lib/BasicEvaluatedExpression.js index eab51de83..65db864f9 100644 --- a/node_modules/webpack/lib/BasicEvaluatedExpression.js +++ b/node_modules/webpack/lib/BasicEvaluatedExpression.js @@ -1,203 +1,211 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-
-"use strict";
-
-class BasicEvaluatedExpression {
-
- constructor() {
- this.range = null;
- }
-
- isNull() {
- return !!this.null;
- }
-
- isString() {
- return Object.prototype.hasOwnProperty.call(this, "string");
- }
-
- isNumber() {
- return Object.prototype.hasOwnProperty.call(this, "number");
- }
-
- isBoolean() {
- return Object.prototype.hasOwnProperty.call(this, "bool");
- }
-
- isRegExp() {
- return Object.prototype.hasOwnProperty.call(this, "regExp");
- }
-
- isConditional() {
- return Object.prototype.hasOwnProperty.call(this, "options");
- }
-
- isArray() {
- return Object.prototype.hasOwnProperty.call(this, "items");
- }
-
- isConstArray() {
- return Object.prototype.hasOwnProperty.call(this, "array");
- }
-
- isIdentifier() {
- return Object.prototype.hasOwnProperty.call(this, "identifier");
- }
-
- isWrapped() {
- return Object.prototype.hasOwnProperty.call(this, "prefix") || Object.prototype.hasOwnProperty.call(this, "postfix");
- }
-
- isTemplateString() {
- return Object.prototype.hasOwnProperty.call(this, "quasis");
- }
-
- isTruthy() {
- return this.truthy;
- }
-
- isFalsy() {
- return this.falsy;
- }
-
- asBool() {
- if(this.truthy) return true;
- else if(this.falsy) return false;
- else if(this.isBoolean()) return this.bool;
- else if(this.isNull()) return false;
- else if(this.isString()) return !!this.string;
- else if(this.isNumber()) return !!this.number;
- else if(this.isRegExp()) return true;
- else if(this.isArray()) return true;
- else if(this.isConstArray()) return true;
- else if(this.isWrapped()) return this.prefix && this.prefix.asBool() || this.postfix && this.postfix.asBool() ? true : undefined;
- else if(this.isTemplateString()) {
- if(this.quasis.length === 1) return this.quasis[0].asBool();
- for(let i = 0; i < this.quasis.length; i++) {
- if(this.quasis[i].asBool()) return true;
- }
- // can't tell if string will be empty without executing
- }
- return undefined;
- }
-
- setString(str) {
- if(str === null)
- delete this.string;
- else
- this.string = str;
- return this;
- }
-
- setNull() {
- this.null = true;
- return this;
- }
-
- setNumber(num) {
- if(num === null)
- delete this.number;
- else
- this.number = num;
- return this;
- }
-
- setBoolean(bool) {
- if(bool === null)
- delete this.bool;
- else
- this.bool = bool;
- return this;
- }
-
- setRegExp(regExp) {
- if(regExp === null)
- delete this.regExp;
- else
- this.regExp = regExp;
- return this;
- }
-
- setIdentifier(identifier) {
- if(identifier === null)
- delete this.identifier;
- else
- this.identifier = identifier;
- return this;
- }
-
- setWrapped(prefix, postfix) {
- this.prefix = prefix;
- this.postfix = postfix;
- return this;
- }
-
- unsetWrapped() {
- delete this.prefix;
- delete this.postfix;
- return this;
- }
-
- setOptions(options) {
- if(options === null)
- delete this.options;
- else
- this.options = options;
- return this;
- }
-
- setItems(items) {
- if(items === null)
- delete this.items;
- else
- this.items = items;
- return this;
- }
-
- setArray(array) {
- if(array === null)
- delete this.array;
- else
- this.array = array;
- return this;
- }
-
- setTemplateString(quasis) {
- if(quasis === null)
- delete this.quasis;
- else
- this.quasis = quasis;
- return this;
- }
-
- setTruthy() {
- this.falsy = false;
- this.truthy = true;
- return this;
- }
-
- setFalsy() {
- this.falsy = true;
- this.truthy = false;
- return this;
- }
-
- addOptions(options) {
- if(!this.options) this.options = [];
- options.forEach(item => {
- this.options.push(item);
- }, this);
- return this;
- }
-
- setRange(range) {
- this.range = range;
- return this;
- }
-
-}
-
-module.exports = BasicEvaluatedExpression;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const TypeUnknown = 0; +const TypeNull = 1; +const TypeString = 2; +const TypeNumber = 3; +const TypeBoolean = 4; +const TypeRegExp = 5; +const TypeConditional = 6; +const TypeArray = 7; +const TypeConstArray = 8; +const TypeIdentifier = 9; +const TypeWrapped = 10; +const TypeTemplateString = 11; + +class BasicEvaluatedExpression { + constructor() { + this.type = TypeUnknown; + this.range = null; + this.falsy = false; + this.truthy = false; + this.bool = null; + this.number = null; + this.regExp = null; + this.string = null; + this.quasis = null; + this.array = null; + this.items = null; + this.options = null; + this.prefix = null; + this.postfix = null; + } + + isNull() { + return this.type === TypeNull; + } + + isString() { + return this.type === TypeString; + } + + isNumber() { + return this.type === TypeNumber; + } + + isBoolean() { + return this.type === TypeBoolean; + } + + isRegExp() { + return this.type === TypeRegExp; + } + + isConditional() { + return this.type === TypeConditional; + } + + isArray() { + return this.type === TypeArray; + } + + isConstArray() { + return this.type === TypeConstArray; + } + + isIdentifier() { + return this.type === TypeIdentifier; + } + + isWrapped() { + return this.type === TypeWrapped; + } + + isTemplateString() { + return this.type === TypeTemplateString; + } + + isTruthy() { + return this.truthy; + } + + isFalsy() { + return this.falsy; + } + + asBool() { + if (this.truthy) return true; + if (this.falsy) return false; + if (this.isBoolean()) return this.bool; + if (this.isNull()) return false; + if (this.isString()) return this.string !== ""; + if (this.isNumber()) return this.number !== 0; + if (this.isRegExp()) return true; + if (this.isArray()) return true; + if (this.isConstArray()) return true; + if (this.isWrapped()) { + return (this.prefix && this.prefix.asBool()) || + (this.postfix && this.postfix.asBool()) + ? true + : undefined; + } + if (this.isTemplateString()) { + for (const quasi of this.quasis) { + if (quasi.asBool()) return true; + } + // can't tell if string will be empty without executing + } + return undefined; + } + + setString(string) { + this.type = TypeString; + this.string = string; + return this; + } + + setNull() { + this.type = TypeNull; + return this; + } + + setNumber(number) { + this.type = TypeNumber; + this.number = number; + return this; + } + + setBoolean(bool) { + this.type = TypeBoolean; + this.bool = bool; + return this; + } + + setRegExp(regExp) { + this.type = TypeRegExp; + this.regExp = regExp; + return this; + } + + setIdentifier(identifier) { + this.type = TypeIdentifier; + this.identifier = identifier; + return this; + } + + setWrapped(prefix, postfix) { + this.type = TypeWrapped; + this.prefix = prefix; + this.postfix = postfix; + return this; + } + + setOptions(options) { + this.type = TypeConditional; + this.options = options; + return this; + } + + addOptions(options) { + if (!this.options) { + this.type = TypeConditional; + this.options = []; + } + for (const item of options) { + this.options.push(item); + } + return this; + } + + setItems(items) { + this.type = TypeArray; + this.items = items; + return this; + } + + setArray(array) { + this.type = TypeConstArray; + this.array = array; + return this; + } + + setTemplateString(quasis) { + this.type = TypeTemplateString; + this.quasis = quasis; + return this; + } + + setTruthy() { + this.falsy = false; + this.truthy = true; + return this; + } + + setFalsy() { + this.falsy = true; + this.truthy = false; + return this; + } + + setRange(range) { + this.range = range; + return this; + } +} + +module.exports = BasicEvaluatedExpression; diff --git a/node_modules/webpack/lib/CachePlugin.js b/node_modules/webpack/lib/CachePlugin.js index 9c19b8140..0d1650be9 100644 --- a/node_modules/webpack/lib/CachePlugin.js +++ b/node_modules/webpack/lib/CachePlugin.js @@ -1,95 +1,102 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const asyncLib = require("async");
-
-class CachePlugin {
- constructor(cache) {
- this.cache = cache || {};
- this.FS_ACCURENCY = 2000;
- }
-
- apply(compiler) {
- if(Array.isArray(compiler.compilers)) {
- compiler.compilers.forEach((c, idx) => {
- c.apply(new CachePlugin(this.cache[idx] = this.cache[idx] || {}));
- });
- } else {
- const registerCacheToCompiler = (compiler, cache) => {
- compiler.plugin("this-compilation", compilation => {
- // TODO remove notCacheable for webpack 4
- if(!compilation.notCacheable) {
- compilation.cache = cache;
- compilation.plugin("child-compiler", (childCompiler, compilerName, compilerIndex) => {
- if(cache) {
- let childCache;
- if(!cache.children) cache.children = {};
- if(!cache.children[compilerName]) cache.children[compilerName] = [];
- if(cache.children[compilerName][compilerIndex])
- childCache = cache.children[compilerName][compilerIndex];
- else
- cache.children[compilerName].push(childCache = {});
- registerCacheToCompiler(childCompiler, childCache);
- }
- });
- } else if(this.watching) {
- compilation.warnings.push(
- new Error(`CachePlugin - Cache cannot be used because of: ${compilation.notCacheable}`)
- );
- }
- });
- };
- registerCacheToCompiler(compiler, this.cache);
- compiler.plugin("watch-run", (compiler, callback) => {
- this.watching = true;
- callback();
- });
- compiler.plugin("run", (compiler, callback) => {
- if(!compiler._lastCompilationFileDependencies) return callback();
- const fs = compiler.inputFileSystem;
- const fileTs = compiler.fileTimestamps = {};
- asyncLib.forEach(compiler._lastCompilationFileDependencies, (file, callback) => {
- fs.stat(file, (err, stat) => {
- if(err) {
- if(err.code === "ENOENT") return callback();
- return callback(err);
- }
-
- if(stat.mtime)
- this.applyMtime(+stat.mtime);
-
- fileTs[file] = +stat.mtime || Infinity;
- callback();
- });
- }, err => {
- if(err) return callback(err);
- Object.keys(fileTs).forEach(key => {
- fileTs[key] += this.FS_ACCURENCY;
- });
- callback();
- });
- });
- compiler.plugin("after-compile", function(compilation, callback) {
- compilation.compiler._lastCompilationFileDependencies = compilation.fileDependencies;
- compilation.compiler._lastCompilationContextDependencies = compilation.contextDependencies;
- callback();
- });
- }
- }
-
- /* istanbul ignore next */
- applyMtime(mtime) {
- if(this.FS_ACCURENCY > 1 && mtime % 2 !== 0)
- this.FS_ACCURENCY = 1;
- else if(this.FS_ACCURENCY > 10 && mtime % 20 !== 0)
- this.FS_ACCURENCY = 10;
- else if(this.FS_ACCURENCY > 100 && mtime % 200 !== 0)
- this.FS_ACCURENCY = 100;
- else if(this.FS_ACCURENCY > 1000 && mtime % 2000 !== 0)
- this.FS_ACCURENCY = 1000;
- }
-}
-module.exports = CachePlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const asyncLib = require("neo-async"); + +class CachePlugin { + constructor(cache) { + this.cache = cache || {}; + this.FS_ACCURACY = 2000; + } + + apply(compiler) { + if (Array.isArray(compiler.compilers)) { + compiler.compilers.forEach((c, idx) => { + new CachePlugin((this.cache[idx] = this.cache[idx] || {})).apply(c); + }); + } else { + const registerCacheToCompiler = (compiler, cache) => { + compiler.hooks.thisCompilation.tap("CachePlugin", compilation => { + compilation.cache = cache; + compilation.hooks.childCompiler.tap( + "CachePlugin", + (childCompiler, compilerName, compilerIndex) => { + if (cache) { + let childCache; + if (!cache.children) { + cache.children = {}; + } + if (!cache.children[compilerName]) { + cache.children[compilerName] = []; + } + if (cache.children[compilerName][compilerIndex]) { + childCache = cache.children[compilerName][compilerIndex]; + } else { + cache.children[compilerName].push((childCache = {})); + } + registerCacheToCompiler(childCompiler, childCache); + } + } + ); + }); + }; + registerCacheToCompiler(compiler, this.cache); + compiler.hooks.watchRun.tap("CachePlugin", () => { + this.watching = true; + }); + compiler.hooks.run.tapAsync("CachePlugin", (compiler, callback) => { + if (!compiler._lastCompilationFileDependencies) { + return callback(); + } + const fs = compiler.inputFileSystem; + const fileTs = (compiler.fileTimestamps = new Map()); + asyncLib.forEach( + compiler._lastCompilationFileDependencies, + (file, callback) => { + fs.stat(file, (err, stat) => { + if (err) { + if (err.code === "ENOENT") return callback(); + return callback(err); + } + + if (stat.mtime) this.applyMtime(+stat.mtime); + + fileTs.set(file, +stat.mtime || Infinity); + + callback(); + }); + }, + err => { + if (err) return callback(err); + + for (const [file, ts] of fileTs) { + fileTs.set(file, ts + this.FS_ACCURACY); + } + + callback(); + } + ); + }); + compiler.hooks.afterCompile.tap("CachePlugin", compilation => { + compilation.compiler._lastCompilationFileDependencies = + compilation.fileDependencies; + compilation.compiler._lastCompilationContextDependencies = + compilation.contextDependencies; + }); + } + } + + /* istanbul ignore next */ + applyMtime(mtime) { + if (this.FS_ACCURACY > 1 && mtime % 2 !== 0) this.FS_ACCURACY = 1; + else if (this.FS_ACCURACY > 10 && mtime % 20 !== 0) this.FS_ACCURACY = 10; + else if (this.FS_ACCURACY > 100 && mtime % 200 !== 0) + this.FS_ACCURACY = 100; + else if (this.FS_ACCURACY > 1000 && mtime % 2000 !== 0) + this.FS_ACCURACY = 1000; + } +} +module.exports = CachePlugin; diff --git a/node_modules/webpack/lib/CaseSensitiveModulesWarning.js b/node_modules/webpack/lib/CaseSensitiveModulesWarning.js index 0cba12ca6..6bfeeca83 100644 --- a/node_modules/webpack/lib/CaseSensitiveModulesWarning.js +++ b/node_modules/webpack/lib/CaseSensitiveModulesWarning.js @@ -1,49 +1,67 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const WebpackError = require("./WebpackError");
-
-module.exports = class CaseSensitiveModulesWarning extends WebpackError {
- constructor(modules) {
- super();
-
- this.name = "CaseSensitiveModulesWarning";
- const sortedModules = this._sort(modules);
- const modulesList = this._moduleMessages(sortedModules);
- this.message = "There are multiple modules with names that only differ in casing.\n" +
- "This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.\n" +
- `Use equal casing. Compare these module identifiers:\n${modulesList}`;
- this.origin = this.module = sortedModules[0];
-
- Error.captureStackTrace(this, this.constructor);
- }
-
- _sort(modules) {
- return modules.slice().sort((a, b) => {
- a = a.identifier();
- b = b.identifier();
- /* istanbul ignore next */
- if(a < b) return -1;
- /* istanbul ignore next */
- if(a > b) return 1;
- /* istanbul ignore next */
- return 0;
- });
- }
-
- _moduleMessages(modules) {
- return modules.map((m) => {
- let message = `* ${m.identifier()}`;
- const validReasons = m.reasons.filter((reason) => reason.module);
-
- if(validReasons.length > 0) {
- message += `\n Used by ${validReasons.length} module(s), i. e.`;
- message += `\n ${validReasons[0].module.identifier()}`;
- }
- return message;
- }).join("\n");
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const WebpackError = require("./WebpackError"); + +/** @typedef {import("./Module")} Module */ + +/** + * @param {Module[]} modules the modules to be sorted + * @returns {Module[]} sorted version of original modules + */ +const sortModules = modules => { + return modules.slice().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 + * @returns {string} each message from provided moduels + */ +const createModulesListMessage = modules => { + return modules + .map(m => { + let message = `* ${m.identifier()}`; + const validReasons = m.reasons.filter(reason => reason.module); + + if (validReasons.length > 0) { + message += `\n Used by ${validReasons.length} module(s), i. e.`; + message += `\n ${validReasons[0].module.identifier()}`; + } + return message; + }) + .join("\n"); +}; + +class CaseSensitiveModulesWarning extends WebpackError { + /** + * Creates an instance of CaseSensitiveModulesWarning. + * @param {Module[]} modules modules that were detected + */ + constructor(modules) { + const sortedModules = sortModules(modules); + const modulesList = createModulesListMessage(sortedModules); + 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.origin = this.module = sortedModules[0]; + + Error.captureStackTrace(this, this.constructor); + } +} + +module.exports = CaseSensitiveModulesWarning; diff --git a/node_modules/webpack/lib/Chunk.js b/node_modules/webpack/lib/Chunk.js index 48ca2d1a3..f0bb2ea72 100644 --- a/node_modules/webpack/lib/Chunk.js +++ b/node_modules/webpack/lib/Chunk.js @@ -1,479 +1,833 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const util = require("util");
-const compareLocations = require("./compareLocations");
-const SortableSet = require("./util/SortableSet");
-let debugId = 1000;
-
-const sortById = (a, b) => {
- if(a.id < b.id) return -1;
- if(b.id < a.id) return 1;
- return 0;
-};
-
-const sortByIdentifier = (a, b) => {
- if(a.identifier() > b.identifier()) return 1;
- if(a.identifier() < b.identifier()) return -1;
- return 0;
-};
-
-class Chunk {
-
- constructor(name, module, loc) {
- this.id = null;
- this.ids = null;
- this.debugId = debugId++;
- this.name = name;
- this._modules = new SortableSet(undefined, sortByIdentifier);
- this.entrypoints = [];
- this.chunks = [];
- this.parents = [];
- this.blocks = [];
- this.origins = [];
- this.files = [];
- this.rendered = false;
- if(module) {
- this.origins.push({
- module,
- loc,
- name
- });
- }
- }
-
- get entry() {
- throw new Error("Chunk.entry was removed. Use hasRuntime()");
- }
-
- set entry(data) {
- throw new Error("Chunk.entry was removed. Use hasRuntime()");
- }
-
- get initial() {
- throw new Error("Chunk.initial was removed. Use isInitial()");
- }
-
- set initial(data) {
- throw new Error("Chunk.initial was removed. Use isInitial()");
- }
-
- hasRuntime() {
- if(this.entrypoints.length === 0) return false;
- return this.entrypoints[0].chunks[0] === this;
- }
-
- isInitial() {
- return this.entrypoints.length > 0;
- }
-
- hasEntryModule() {
- return !!this.entryModule;
- }
-
- addToCollection(collection, item) {
- if(item === this) {
- return false;
- }
-
- if(collection.indexOf(item) > -1) {
- return false;
- }
-
- collection.push(item);
- return true;
- }
-
- addChunk(chunk) {
- return this.addToCollection(this.chunks, chunk);
- }
-
- addParent(parentChunk) {
- return this.addToCollection(this.parents, parentChunk);
- }
-
- addModule(module) {
- if(!this._modules.has(module)) {
- this._modules.add(module);
- return true;
- }
- return false;
- }
-
- addBlock(block) {
- return this.addToCollection(this.blocks, block);
- }
-
- removeModule(module) {
- if(this._modules.delete(module)) {
- module.removeChunk(this);
- return true;
- }
- return false;
- }
-
- removeChunk(chunk) {
- const idx = this.chunks.indexOf(chunk);
- if(idx >= 0) {
- this.chunks.splice(idx, 1);
- chunk.removeParent(this);
- return true;
- }
- return false;
- }
-
- removeParent(chunk) {
- const idx = this.parents.indexOf(chunk);
- if(idx >= 0) {
- this.parents.splice(idx, 1);
- chunk.removeChunk(this);
- return true;
- }
- return false;
- }
-
- addOrigin(module, loc) {
- this.origins.push({
- module,
- loc,
- name: this.name
- });
- }
-
- setModules(modules) {
- this._modules = new SortableSet(modules, sortByIdentifier);
- }
-
- getNumberOfModules() {
- return this._modules.size;
- }
-
- get modulesIterable() {
- return this._modules;
- }
-
- forEachModule(fn) {
- this._modules.forEach(fn);
- }
-
- mapModules(fn) {
- return Array.from(this._modules, fn);
- }
-
- compareTo(otherChunk) {
- this._modules.sort();
- otherChunk._modules.sort();
- if(this._modules.size > otherChunk._modules.size) return -1;
- if(this._modules.size < otherChunk._modules.size) return 1;
- const a = this._modules[Symbol.iterator]();
- const b = otherChunk._modules[Symbol.iterator]();
- while(true) { // eslint-disable-line
- const aItem = a.next();
- const bItem = b.next();
- if(aItem.done) return 0;
- const aModuleIdentifier = aItem.value.identifier();
- const bModuleIdentifier = bItem.value.identifier();
- if(aModuleIdentifier > bModuleIdentifier) return -1;
- if(aModuleIdentifier < bModuleIdentifier) return 1;
- }
- }
-
- containsModule(module) {
- return this._modules.has(module);
- }
-
- getModules() {
- return Array.from(this._modules);
- }
-
- getModulesIdent() {
- this._modules.sort();
- let str = "";
- this._modules.forEach(m => {
- str += m.identifier() + "#";
- });
- return str;
- }
-
- remove(reason) {
- // cleanup modules
- // Array.from is used here to create a clone, because removeChunk modifies this._modules
- Array.from(this._modules).forEach(module => {
- module.removeChunk(this);
- });
-
- // cleanup parents
- this.parents.forEach(parentChunk => {
- // remove this chunk from its parents
- const idx = parentChunk.chunks.indexOf(this);
- if(idx >= 0) {
- parentChunk.chunks.splice(idx, 1);
- }
-
- // cleanup "sub chunks"
- this.chunks.forEach(chunk => {
- /**
- * remove this chunk as "intermediary" and connect
- * it "sub chunks" and parents directly
- */
- // add parent to each "sub chunk"
- chunk.addParent(parentChunk);
- // add "sub chunk" to parent
- parentChunk.addChunk(chunk);
- });
- });
-
- /**
- * we need to iterate again over the chunks
- * to remove this from the chunks parents.
- * This can not be done in the above loop
- * as it is not garuanteed that `this.parents` contains anything.
- */
- this.chunks.forEach(chunk => {
- // remove this as parent of every "sub chunk"
- const idx = chunk.parents.indexOf(this);
- if(idx >= 0) {
- chunk.parents.splice(idx, 1);
- }
- });
-
- // cleanup blocks
- this.blocks.forEach(block => {
- const idx = block.chunks.indexOf(this);
- if(idx >= 0) {
- block.chunks.splice(idx, 1);
- if(block.chunks.length === 0) {
- block.chunks = null;
- block.chunkReason = reason;
- }
- }
- });
- }
-
- moveModule(module, otherChunk) {
- module.removeChunk(this);
- module.addChunk(otherChunk);
- otherChunk.addModule(module);
- module.rewriteChunkInReasons(this, [otherChunk]);
- }
-
- replaceChunk(oldChunk, newChunk) {
- const idx = this.chunks.indexOf(oldChunk);
- if(idx >= 0) {
- this.chunks.splice(idx, 1);
- }
- if(this !== newChunk && newChunk.addParent(this)) {
- this.addChunk(newChunk);
- }
- }
-
- replaceParentChunk(oldParentChunk, newParentChunk) {
- const idx = this.parents.indexOf(oldParentChunk);
- if(idx >= 0) {
- this.parents.splice(idx, 1);
- }
- if(this !== newParentChunk && newParentChunk.addChunk(this)) {
- this.addParent(newParentChunk);
- }
- }
-
- integrate(otherChunk, reason) {
- if(!this.canBeIntegrated(otherChunk)) {
- return false;
- }
-
- // Array.from is used here to create a clone, because moveModule modifies otherChunk._modules
- const otherChunkModules = Array.from(otherChunk._modules);
- otherChunkModules.forEach(module => otherChunk.moveModule(module, this));
- otherChunk._modules.clear();
-
- otherChunk.parents.forEach(parentChunk => parentChunk.replaceChunk(otherChunk, this));
- otherChunk.parents.length = 0;
-
- otherChunk.chunks.forEach(chunk => chunk.replaceParentChunk(otherChunk, this));
- otherChunk.chunks.length = 0;
-
- otherChunk.blocks.forEach(b => {
- b.chunks = b.chunks ? b.chunks.map(c => {
- return c === otherChunk ? this : c;
- }) : [this];
- b.chunkReason = reason;
- this.addBlock(b);
- });
- otherChunk.blocks.length = 0;
-
- otherChunk.origins.forEach(origin => {
- this.origins.push(origin);
- });
- this.blocks.forEach(b => {
- b.chunkReason = reason;
- });
- this.origins.forEach(origin => {
- if(!origin.reasons) {
- origin.reasons = [reason];
- } else if(origin.reasons[0] !== reason) {
- origin.reasons.unshift(reason);
- }
- });
- this.chunks = this.chunks.filter(chunk => {
- return chunk !== otherChunk && chunk !== this;
- });
- this.parents = this.parents.filter(parentChunk => {
- return parentChunk !== otherChunk && parentChunk !== this;
- });
- return true;
- }
-
- split(newChunk) {
- this.blocks.forEach(block => {
- newChunk.blocks.push(block);
- block.chunks.push(newChunk);
- });
- this.chunks.forEach(chunk => {
- newChunk.chunks.push(chunk);
- chunk.parents.push(newChunk);
- });
- this.parents.forEach(parentChunk => {
- parentChunk.chunks.push(newChunk);
- newChunk.parents.push(parentChunk);
- });
- this.entrypoints.forEach(entrypoint => {
- entrypoint.insertChunk(newChunk, this);
- });
- }
-
- isEmpty() {
- return this._modules.size === 0;
- }
-
- updateHash(hash) {
- hash.update(`${this.id} `);
- hash.update(this.ids ? this.ids.join(",") : "");
- hash.update(`${this.name || ""} `);
- this._modules.forEach(m => m.updateHash(hash));
- }
-
- canBeIntegrated(otherChunk) {
- if(otherChunk.isInitial()) {
- return false;
- }
- if(this.isInitial()) {
- if(otherChunk.parents.length !== 1 || otherChunk.parents[0] !== this) {
- return false;
- }
- }
- return true;
- }
-
- addMultiplierAndOverhead(size, options) {
- const overhead = typeof options.chunkOverhead === "number" ? options.chunkOverhead : 10000;
- const multiplicator = this.isInitial() ? (options.entryChunkMultiplicator || 10) : 1;
-
- return size * multiplicator + overhead;
- }
-
- modulesSize() {
- let count = 0;
- for(const module of this._modules) {
- count += module.size();
- }
- return count;
- }
-
- size(options) {
- return this.addMultiplierAndOverhead(this.modulesSize(), options);
- }
-
- integratedSize(otherChunk, options) {
- // Chunk if it's possible to integrate this chunk
- if(!this.canBeIntegrated(otherChunk)) {
- return false;
- }
-
- let integratedModulesSize = this.modulesSize();
- // only count modules that do not exist in this chunk!
- for(const otherModule of otherChunk._modules) {
- if(!this._modules.has(otherModule)) {
- integratedModulesSize += otherModule.size();
- }
- }
-
- return this.addMultiplierAndOverhead(integratedModulesSize, options);
- }
-
- getChunkMaps(includeEntries, realHash) {
- const chunksProcessed = [];
- const chunkHashMap = {};
- const chunkNameMap = {};
- (function addChunk(chunk) {
- if(chunksProcessed.indexOf(chunk) >= 0) return;
- chunksProcessed.push(chunk);
- if(!chunk.hasRuntime() || includeEntries) {
- chunkHashMap[chunk.id] = realHash ? chunk.hash : chunk.renderedHash;
- if(chunk.name)
- chunkNameMap[chunk.id] = chunk.name;
- }
- chunk.chunks.forEach(addChunk);
- }(this));
- return {
- hash: chunkHashMap,
- name: chunkNameMap
- };
- }
-
- sortModules(sortByFn) {
- this._modules.sortWith(sortByFn || sortById);
- }
-
- sortItems() {
- this.sortModules();
- this.origins.sort((a, b) => {
- const aIdent = a.module.identifier();
- const bIdent = b.module.identifier();
- if(aIdent < bIdent) return -1;
- if(aIdent > bIdent) return 1;
- return compareLocations(a.loc, b.loc);
- });
- this.origins.forEach(origin => {
- if(origin.reasons)
- origin.reasons.sort();
- });
- this.parents.sort(sortById);
- this.chunks.sort(sortById);
- }
-
- toString() {
- return `Chunk[${Array.from(this._modules).join()}]`;
- }
-
- checkConstraints() {
- const chunk = this;
- chunk.chunks.forEach((child, idx) => {
- if(chunk.chunks.indexOf(child) !== idx)
- throw new Error(`checkConstraints: duplicate child in chunk ${chunk.debugId} ${child.debugId}`);
- if(child.parents.indexOf(chunk) < 0)
- throw new Error(`checkConstraints: child missing parent ${chunk.debugId} -> ${child.debugId}`);
- });
- chunk.parents.forEach((parentChunk, idx) => {
- if(chunk.parents.indexOf(parentChunk) !== idx)
- throw new Error(`checkConstraints: duplicate parent in chunk ${chunk.debugId} ${parentChunk.debugId}`);
- if(parentChunk.chunks.indexOf(chunk) < 0)
- throw new Error(`checkConstraints: parent missing child ${parentChunk.debugId} <- ${chunk.debugId}`);
- });
- }
-}
-
-Object.defineProperty(Chunk.prototype, "modules", {
- configurable: false,
- get: util.deprecate(function() {
- return Array.from(this._modules);
- }, "Chunk.modules is deprecated. Use Chunk.getNumberOfModules/mapModules/forEachModule/containsModule instead."),
- set: util.deprecate(function(value) {
- this.setModules(value);
- }, "Chunk.modules is deprecated. Use Chunk.addModule/removeModule instead.")
-});
-
-module.exports = Chunk;
+/* +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 intersect = require("./util/SetHelpers").intersect; +const GraphHelpers = require("./GraphHelpers"); +const Entrypoint = require("./Entrypoint"); +let debugId = 1000; +const ERR_CHUNK_ENTRY = "Chunk.entry was removed. Use hasRuntime()"; +const ERR_CHUNK_INITIAL = + "Chunk.initial was removed. Use canBeInitial/isOnlyInitial()"; + +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./ChunkGroup")} ChunkGroup */ +/** @typedef {import("./ModuleReason")} ModuleReason */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("./util/createHash").Hash} Hash */ + +/** + * @typedef {Object} WithId an object who has an id property * + * @property {string | number} id the id of the object + */ + +/** + * Compare two Modules based on their ids for sorting + * @param {Module} a module + * @param {Module} b module + * @returns {-1|0|1} sort value + */ + +// TODO use @callback +/** @typedef {(a: Module, b: Module) => -1|0|1} ModuleSortPredicate */ +/** @typedef {(m: Module) => boolean} ModuleFilterPredicate */ +/** @typedef {(c: Chunk) => boolean} ChunkFilterPredicate */ + +const sortModuleById = (a, b) => { + if (a.id < b.id) return -1; + if (b.id < a.id) return 1; + return 0; +}; + +/** + * Compare two ChunkGroups based on their ids for sorting + * @param {ChunkGroup} a chunk group + * @param {ChunkGroup} b chunk group + * @returns {-1|0|1} sort value + */ +const sortChunkGroupById = (a, b) => { + if (a.id < b.id) return -1; + if (b.id < a.id) return 1; + return 0; +}; + +/** + * Compare two Identifiables , based on their ids for sorting + * @param {Module} a first object with ident fn + * @param {Module} b second object with ident fn + * @returns {-1|0|1} The order number of the sort + */ +const sortByIdentifier = (a, b) => { + if (a.identifier() > b.identifier()) return 1; + if (a.identifier() < b.identifier()) return -1; + return 0; +}; + +/** + * @returns {string} a concatenation of module identifiers sorted + * @param {SortableSet} set to pull module identifiers from + */ +const getModulesIdent = set => { + set.sort(); + let str = ""; + for (const m of set) { + str += m.identifier() + "#"; + } + return str; +}; + +/** + * @template T + * @param {SortableSet<T>} set the sortable set to convert to array + * @returns {Array<T>} the array returned from Array.from(set) + */ +const getArray = set => Array.from(set); + +/** + * @param {SortableSet<Module>} set the sortable Set to get the count/size of + * @returns {number} the size of the modules + */ +const getModulesSize = set => { + let size = 0; + for (const module of set) { + size += module.size(); + } + return size; +}; + +/** + * 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) + */ + constructor(name) { + /** @type {number | null} */ + this.id = null; + /** @type {number[] | null} */ + this.ids = null; + /** @type {number} */ + this.debugId = debugId++; + /** @type {string} */ + this.name = name; + /** @type {boolean} */ + this.preventIntegration = false; + /** @type {Module=} */ + this.entryModule = undefined; + /** @private @type {SortableSet<Module>} */ + this._modules = new SortableSet(undefined, sortByIdentifier); + /** @type {string?} */ + this.filenameTemplate = undefined; + /** @private @type {SortableSet<ChunkGroup>} */ + this._groups = new SortableSet(undefined, sortChunkGroupById); + /** @type {string[]} */ + this.files = []; + /** @type {boolean} */ + this.rendered = false; + /** @type {string=} */ + this.hash = undefined; + /** @type {Object} */ + this.contentHash = Object.create(null); + /** @type {string=} */ + this.renderedHash = undefined; + /** @type {string=} */ + this.chunkReason = undefined; + /** @type {boolean} */ + this.extraAsync = false; + this.removedModules = undefined; + } + + /** + * @deprecated Chunk.entry has been deprecated. Please use .hasRuntime() instead + * @returns {never} Throws an error trying to access this property + */ + get entry() { + throw new Error(ERR_CHUNK_ENTRY); + } + + /** + * @deprecated .entry has been deprecated. Please use .hasRuntime() instead + * @param {never} data The data that was attempting to be set + * @returns {never} Throws an error trying to access this property + */ + set entry(data) { + throw new Error(ERR_CHUNK_ENTRY); + } + + /** + * @deprecated Chunk.initial was removed. Use canBeInitial/isOnlyInitial() + * @returns {never} Throws an error trying to access this property + */ + get initial() { + throw new Error(ERR_CHUNK_INITIAL); + } + + /** + * @deprecated Chunk.initial was removed. Use canBeInitial/isOnlyInitial() + * @param {never} data The data attempting to be set + * @returns {never} Throws an error trying to access this property + */ + set initial(data) { + throw new Error(ERR_CHUNK_INITIAL); + } + + /** + * @returns {boolean} whether or not the Chunk will have a runtime + */ + hasRuntime() { + for (const chunkGroup of this._groups) { + // We only need to check the first one + return ( + chunkGroup.isInitial() && + chunkGroup instanceof Entrypoint && + chunkGroup.getRuntimeChunk() === this + ); + } + 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 {boolean} if this chunk contains the entry module + */ + hasEntryModule() { + return !!this.entryModule; + } + + /** + * @param {Module} module the module that will be added to this chunk. + * @returns {boolean} returns true if the chunk doesn't have the module and it was added + */ + addModule(module) { + if (!this._modules.has(module)) { + this._modules.add(module); + return true; + } + return false; + } + + /** + * @param {Module} module the module that will be removed from this chunk + * @returns {boolean} returns true if chunk exists and is successfully deleted + */ + removeModule(module) { + if (this._modules.delete(module)) { + module.removeChunk(this); + return true; + } + return false; + } + + /** + * @param {Module[]} modules the new modules to be set + * @returns {void} set new modules to this chunk and return nothing + */ + setModules(modules) { + this._modules = new SortableSet(modules, sortByIdentifier); + } + + /** + * @returns {number} the amount of modules in chunk + */ + getNumberOfModules() { + return this._modules.size; + } + + /** + * @returns {SortableSet} return the modules SortableSet for this chunk + */ + get modulesIterable() { + return this._modules; + } + + /** + * @param {ChunkGroup} chunkGroup the chunkGroup the chunk is being added + * @returns {boolean} returns true if chunk is not apart of chunkGroup and is added successfully + */ + addGroup(chunkGroup) { + if (this._groups.has(chunkGroup)) return false; + this._groups.add(chunkGroup); + return true; + } + + /** + * @param {ChunkGroup} chunkGroup the chunkGroup the chunk is being removed from + * @returns {boolean} returns true if chunk does exist in chunkGroup and is removed + */ + removeGroup(chunkGroup) { + if (!this._groups.has(chunkGroup)) return false; + this._groups.delete(chunkGroup); + return true; + } + + /** + * @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 said chunk is in + */ + getNumberOfGroups() { + return this._groups.size; + } + + /** + * @returns {SortableSet<ChunkGroup>} the chunkGroups that said chunk is referenced in + */ + get groupsIterable() { + return this._groups; + } + + /** + * @param {Chunk} otherChunk the chunk to compare itself with + * @returns {-1|0|1} this is a comparitor function like sort and returns -1, 0, or 1 based on sort order + */ + compareTo(otherChunk) { + if (this._modules.size > otherChunk._modules.size) return -1; + if (this._modules.size < otherChunk._modules.size) return 1; + this._modules.sort(); + otherChunk._modules.sort(); + const a = this._modules[Symbol.iterator](); + const b = otherChunk._modules[Symbol.iterator](); + // eslint-disable-next-line no-constant-condition + while (true) { + const aItem = a.next(); + if (aItem.done) return 0; + const bItem = b.next(); + const aModuleIdentifier = aItem.value.identifier(); + const bModuleIdentifier = bItem.value.identifier(); + if (aModuleIdentifier < bModuleIdentifier) return -1; + if (aModuleIdentifier > bModuleIdentifier) return 1; + } + } + + /** + * @param {Module} module Module to check + * @returns {boolean} returns true if module does exist in this chunk + */ + containsModule(module) { + return this._modules.has(module); + } + + getModules() { + return this._modules.getFromCache(getArray); + } + + getModulesIdent() { + return this._modules.getFromUnorderedCache(getModulesIdent); + } + + remove() { + // cleanup modules + // Array.from is used here to create a clone, because removeChunk modifies this._modules + for (const module of Array.from(this._modules)) { + module.removeChunk(this); + } + for (const chunkGroup of this._groups) { + chunkGroup.removeChunk(this); + } + } + + /** + * + * @param {Module} module module to move + * @param {Chunk} otherChunk other chunk to move it to + * @returns {void} + */ + moveModule(module, otherChunk) { + GraphHelpers.disconnectChunkAndModule(this, module); + GraphHelpers.connectChunkAndModule(otherChunk, module); + module.rewriteChunkInReasons(this, [otherChunk]); + } + + /** + * + * @param {Chunk} otherChunk the chunk to integrate with + * @param {ModuleReason} reason reason why the module is being integrated + * @returns {boolean} returns true or false if integration succeeds or fails + */ + integrate(otherChunk, reason) { + if (!this.canBeIntegrated(otherChunk)) { + return false; + } + + // Array.from is used here to create a clone, because moveModule modifies otherChunk._modules + for (const module of Array.from(otherChunk._modules)) { + otherChunk.moveModule(module, this); + } + otherChunk._modules.clear(); + + for (const chunkGroup of otherChunk._groups) { + chunkGroup.replaceChunk(otherChunk, this); + this.addGroup(chunkGroup); + } + otherChunk._groups.clear(); + + if (this.name && otherChunk.name) { + if (this.name.length !== otherChunk.name.length) { + this.name = + this.name.length < otherChunk.name.length + ? this.name + : otherChunk.name; + } else { + this.name = this.name < otherChunk.name ? this.name : otherChunk.name; + } + } + + return true; + } + + /** + * @param {Chunk} newChunk the new chunk that will be split out of, and then chunk raphi twil= + * @returns {void} + */ + split(newChunk) { + for (const chunkGroup of this._groups) { + chunkGroup.insertChunk(newChunk, this); + newChunk.addGroup(chunkGroup); + } + } + + isEmpty() { + return this._modules.size === 0; + } + + updateHash(hash) { + hash.update(`${this.id} `); + hash.update(this.ids ? this.ids.join(",") : ""); + hash.update(`${this.name || ""} `); + for (const m of this._modules) { + hash.update(m.hash); + } + } + + canBeIntegrated(otherChunk) { + const isAvailable = (a, b) => { + const queue = new Set(b.groupsIterable); + for (const chunkGroup of queue) { + if (a.isInGroup(chunkGroup)) continue; + if (chunkGroup.isInitial()) return false; + for (const parent of chunkGroup.parentsIterable) { + queue.add(parent); + } + } + return true; + }; + + if (this.preventIntegration || otherChunk.preventIntegration) { + return false; + } + + if (this.hasRuntime() !== otherChunk.hasRuntime()) { + if (this.hasRuntime()) { + return isAvailable(this, otherChunk); + } else if (otherChunk.hasRuntime()) { + return isAvailable(otherChunk, this); + } else { + return false; + } + } + + if (this.hasEntryModule() || otherChunk.hasEntryModule()) { + return false; + } + + return true; + } + + /** + * + * @param {number} size the size + * @param {Object} options the options passed in + * @returns {number} the multiplier returned + */ + addMultiplierAndOverhead(size, options) { + const overhead = + typeof options.chunkOverhead === "number" ? options.chunkOverhead : 10000; + const multiplicator = this.canBeInitial() + ? options.entryChunkMultiplicator || 10 + : 1; + + return size * multiplicator + overhead; + } + + /** + * @returns {number} the size of all modules + */ + modulesSize() { + return this._modules.getFromUnorderedCache(getModulesSize); + } + + /** + * @param {Object} options the size display options + * @returns {number} the chunk size + */ + size(options) { + return this.addMultiplierAndOverhead(this.modulesSize(), options); + } + + /** + * @param {Chunk} otherChunk the other chunk + * @param {TODO} options the options for this function + * @returns {number | false} the size, or false if it can't be integrated + */ + integratedSize(otherChunk, options) { + // Chunk if it's possible to integrate this chunk + if (!this.canBeIntegrated(otherChunk)) { + return false; + } + + let integratedModulesSize = this.modulesSize(); + // only count modules that do not exist in this chunk! + for (const otherModule of otherChunk._modules) { + if (!this._modules.has(otherModule)) { + integratedModulesSize += otherModule.size(); + } + } + + return this.addMultiplierAndOverhead(integratedModulesSize, options); + } + + /** + * @param {function(Module, Module): -1|0|1=} sortByFn a predicate function used to sort modules + * @returns {void} + */ + sortModules(sortByFn) { + this._modules.sortWith(sortByFn || sortModuleById); + } + + sortItems() { + this.sortModules(); + } + + /** + * @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)) + ); + + 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)) { + chunks.add(chunk); + } + } + for (const child of chunkGroup.childrenIterable) { + queue.add(child); + } + } + + return chunks; + } + + /** + * @typedef {Object} ChunkMaps + * @property {Record<string|number, string>} hash + * @property {Record<string|number, Record<string, string>>} contentHash + * @property {Record<string|number, string>} name + */ + + /** + * @param {boolean} realHash should the full hash or the rendered hash 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()) { + chunkHashMap[chunk.id] = realHash ? chunk.hash : chunk.renderedHash; + for (const key of Object.keys(chunk.contentHash)) { + if (!chunkContentHashMap[key]) { + chunkContentHashMap[key] = Object.create(null); + } + chunkContentHashMap[key][chunk.id] = chunk.contentHash[key]; + } + if (chunk.name) { + chunkNameMap[chunk.id] = chunk.name; + } + } + + return { + hash: chunkHashMap, + contentHash: chunkContentHashMap, + name: chunkNameMap + }; + } + + /** + * @returns {Record<string, Set<TODO>[]>} a record object of names to lists of child ids(?) + */ + getChildIdsByOrders() { + const lists = new Map(); + for (const group of this.groupsIterable) { + if (group.chunks[group.chunks.length - 1] === this) { + for (const childGroup of group.childrenIterable) { + // TODO webpack 5 remove this check for options + if (typeof childGroup.options === "object") { + for (const key of Object.keys(childGroup.options)) { + if (key.endsWith("Order")) { + const name = key.substr(0, key.length - "Order".length); + let list = lists.get(name); + if (list === undefined) lists.set(name, (list = [])); + list.push({ + order: childGroup.options[key], + group: childGroup + }); + } + } + } + } + } + } + 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; + // TODO webpack 5 remove this check of compareTo + if (a.group.compareTo) { + return a.group.compareTo(b.group); + } + return 0; + }); + result[name] = Array.from( + list.reduce((set, item) => { + for (const chunk of item.group.chunks) { + set.add(chunk.id); + } + return set; + }, new Set()) + ); + } + return result; + } + + getChildIdsByOrdersMap(includeDirectChildren) { + const chunkMaps = Object.create(null); + + const addChildIdsByOrdersToMap = chunk => { + const data = chunk.getChildIdsByOrders(); + for (const key of Object.keys(data)) { + let chunkMap = chunkMaps[key]; + if (chunkMap === undefined) { + chunkMaps[key] = chunkMap = Object.create(null); + } + chunkMap[chunk.id] = data[key]; + } + }; + + if (includeDirectChildren) { + addChildIdsByOrdersToMap(this); + } + + for (const chunk of this.getAllAsyncChunks()) { + addChildIdsByOrdersToMap(chunk); + } + + return chunkMaps; + } + + /** + * @typedef {Object} ChunkModuleMaps + * @property {Record<string|number, (string|number)[]>} id + * @property {Record<string|number, string>} hash + */ + + /** + * @param {ModuleFilterPredicate} filterFn function used to filter modules + * @returns {ChunkModuleMaps} module map information + */ + getChunkModuleMaps(filterFn) { + /** @type {Record<string|number, (string|number)[]>} */ + const chunkModuleIdMap = Object.create(null); + /** @type {Record<string|number, string>} */ + const chunkModuleHashMap = Object.create(null); + + for (const chunk of this.getAllAsyncChunks()) { + /** @type {(string|number)[]} */ + let array; + for (const module of chunk.modulesIterable) { + if (filterFn(module)) { + if (array === undefined) { + array = []; + chunkModuleIdMap[chunk.id] = array; + } + array.push(module.id); + chunkModuleHashMap[module.id] = module.renderedHash; + } + } + if (array !== undefined) { + array.sort(); + } + } + + return { + id: chunkModuleIdMap, + hash: chunkModuleHashMap + }; + } + + /** + * + * @param {function(Module): boolean} filterFn predicate function used to filter modules + * @param {function(Chunk): boolean} filterChunkFn predicate function used to filter chunks + * @returns {boolean} return true if module exists in graph + */ + hasModuleInGraph(filterFn, filterChunkFn) { + const queue = new Set(this.groupsIterable); + const chunksProcessed = new Set(); + + for (const chunkGroup of queue) { + for (const chunk of chunkGroup.chunks) { + if (!chunksProcessed.has(chunk)) { + chunksProcessed.add(chunk); + if (!filterChunkFn || filterChunkFn(chunk)) { + for (const module of chunk.modulesIterable) { + if (filterFn(module)) { + return true; + } + } + } + } + } + for (const child of chunkGroup.childrenIterable) { + queue.add(child); + } + } + return false; + } + + toString() { + return `Chunk[${Array.from(this._modules).join()}]`; + } +} + +// TODO remove in webpack 5 +Object.defineProperty(Chunk.prototype, "forEachModule", { + configurable: false, + value: util.deprecate( + /** + * @deprecated + * @this {Chunk} + * @typedef {function(any, any, Set<any>): void} ForEachModuleCallback + * @param {ForEachModuleCallback} fn Callback function + * @returns {void} + */ + function(fn) { + this._modules.forEach(fn); + }, + "Chunk.forEachModule: Use for(const module of chunk.modulesIterable) instead" + ) +}); + +// TODO remove in webpack 5 +Object.defineProperty(Chunk.prototype, "mapModules", { + configurable: false, + value: util.deprecate( + /** + * @deprecated + * @this {Chunk} + * @typedef {function(any, number): any} MapModulesCallback + * @param {MapModulesCallback} fn Callback function + * @returns {TODO[]} result of mapped modules + */ + function(fn) { + return Array.from(this._modules, fn); + }, + "Chunk.mapModules: Use Array.from(chunk.modulesIterable, fn) instead" + ) +}); + +// TODO remove in webpack 5 +Object.defineProperty(Chunk.prototype, "chunks", { + configurable: false, + get() { + throw new Error("Chunk.chunks: Use ChunkGroup.getChildren() instead"); + }, + set() { + throw new Error("Chunk.chunks: Use ChunkGroup.add/removeChild() instead"); + } +}); + +// TODO remove in webpack 5 +Object.defineProperty(Chunk.prototype, "parents", { + configurable: false, + get() { + throw new Error("Chunk.parents: Use ChunkGroup.getParents() instead"); + }, + set() { + throw new Error("Chunk.parents: Use ChunkGroup.add/removeParent() instead"); + } +}); + +// TODO remove in webpack 5 +Object.defineProperty(Chunk.prototype, "blocks", { + configurable: false, + get() { + throw new Error("Chunk.blocks: Use ChunkGroup.getBlocks() instead"); + }, + set() { + throw new Error("Chunk.blocks: Use ChunkGroup.add/removeBlock() instead"); + } +}); + +// TODO remove in webpack 5 +Object.defineProperty(Chunk.prototype, "entrypoints", { + configurable: false, + get() { + throw new Error( + "Chunk.entrypoints: Use Chunks.groupsIterable and filter by instanceof Entrypoint instead" + ); + }, + set() { + throw new Error("Chunk.entrypoints: Use Chunks.addGroup instead"); + } +}); + +module.exports = Chunk; diff --git a/node_modules/webpack/lib/ChunkRenderError.js b/node_modules/webpack/lib/ChunkRenderError.js index 578104b53..0d0eb2cbc 100644 --- a/node_modules/webpack/lib/ChunkRenderError.js +++ b/node_modules/webpack/lib/ChunkRenderError.js @@ -1,24 +1,32 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const WebpackError = require("./WebpackError");
-
-class ChunkRenderError extends WebpackError {
- 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;
-
- Error.captureStackTrace(this, this.constructor);
- }
-}
-
-module.exports = ChunkRenderError;
+/* + 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; + + Error.captureStackTrace(this, this.constructor); + } +} + +module.exports = ChunkRenderError; diff --git a/node_modules/webpack/lib/ChunkTemplate.js b/node_modules/webpack/lib/ChunkTemplate.js index 6bcb8a883..65861af49 100644 --- a/node_modules/webpack/lib/ChunkTemplate.js +++ b/node_modules/webpack/lib/ChunkTemplate.js @@ -1,36 +1,87 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const ConcatSource = require("webpack-sources").ConcatSource;
-const Template = require("./Template");
-
-module.exports = class ChunkTemplate extends Template {
- constructor(outputOptions) {
- super(outputOptions);
- }
-
- render(chunk, moduleTemplate, dependencyTemplates) {
- const moduleSources = this.renderChunkModules(chunk, moduleTemplate, dependencyTemplates);
- const core = this.applyPluginsWaterfall("modules", moduleSources, chunk, moduleTemplate, dependencyTemplates);
- let source = this.applyPluginsWaterfall("render", core, chunk, moduleTemplate, dependencyTemplates);
- if(chunk.hasEntryModule()) {
- source = this.applyPluginsWaterfall("render-with-entry", source, chunk);
- }
- chunk.rendered = true;
- return new ConcatSource(source, ";");
- }
-
- updateHash(hash) {
- hash.update("ChunkTemplate");
- hash.update("2");
- this.applyPlugins("hash", hash);
- }
-
- updateHashForChunk(hash, chunk) {
- this.updateHash(hash);
- this.applyPlugins("hash-for-chunk", hash, chunk);
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const { Tapable, SyncWaterfallHook, SyncHook } = require("tapable"); + +/** @typedef {import("./ModuleTemplate")} ModuleTemplate */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./Module")} Module} */ +/** @typedef {import("./Dependency").DependencyTemplate} DependencyTemplate} */ +/** @typedef {import("./util/createHash").Hash} Hash} */ + +/** + * @typedef {Object} RenderManifestOptions + * @property {Chunk} chunk the chunk used to render + * @property {string} hash + * @property {string} fullHash + * @property {TODO} outputOptions + * @property {{javascript: ModuleTemplate, webassembly: ModuleTemplate}} moduleTemplates + * @property {Map<TODO, TODO>} dependencyTemplates + */ + +module.exports = class ChunkTemplate extends Tapable { + constructor(outputOptions) { + super(); + this.outputOptions = outputOptions || {}; + this.hooks = { + /** @type {SyncWaterfallHook<TODO[], RenderManifestOptions>} */ + renderManifest: new SyncWaterfallHook(["result", "options"]), + modules: new SyncWaterfallHook([ + "source", + "chunk", + "moduleTemplate", + "dependencyTemplates" + ]), + render: new SyncWaterfallHook([ + "source", + "chunk", + "moduleTemplate", + "dependencyTemplates" + ]), + renderWithEntry: new SyncWaterfallHook(["source", "chunk"]), + hash: new SyncHook(["hash"]), + hashForChunk: new SyncHook(["hash", "chunk"]) + }; + } + + /** + * + * @param {RenderManifestOptions} options render manifest options + * @returns {TODO[]} returns render manifest + */ + getRenderManifest(options) { + const result = []; + + this.hooks.renderManifest.call(result, options); + + return result; + } + + /** + * Updates hash with information from this template + * @param {Hash} hash the hash to update + * @returns {void} + */ + updateHash(hash) { + hash.update("ChunkTemplate"); + hash.update("2"); + this.hooks.hash.call(hash); + } + + /** + * TODO webpack 5: remove moduleTemplate and dependencyTemplates + * Updates hash with chunk-specific information from this template + * @param {Hash} hash the hash to update + * @param {Chunk} chunk the chunk + * @param {ModuleTemplate} moduleTemplate ModuleTemplate instance for render + * @param {Map<Function, DependencyTemplate>} dependencyTemplates dependency templates + * @returns {void} + */ + updateHashForChunk(hash, chunk, moduleTemplate, dependencyTemplates) { + this.updateHash(hash); + this.hooks.hashForChunk.call(hash, chunk); + } +}; diff --git a/node_modules/webpack/lib/CompatibilityPlugin.js b/node_modules/webpack/lib/CompatibilityPlugin.js index 847611e9f..1544d6c82 100644 --- a/node_modules/webpack/lib/CompatibilityPlugin.js +++ b/node_modules/webpack/lib/CompatibilityPlugin.js @@ -1,57 +1,70 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const ConstDependency = require("./dependencies/ConstDependency");
-
-const NullFactory = require("./NullFactory");
-
-const jsonLoaderPath = require.resolve("json-loader");
-const matchJson = /\.json$/i;
-
-class CompatibilityPlugin {
-
- apply(compiler) {
- compiler.plugin("compilation", (compilation, params) => {
- compilation.dependencyFactories.set(ConstDependency, new NullFactory());
- compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
-
- params.normalModuleFactory.plugin("parser", (parser, parserOptions) => {
-
- if(typeof parserOptions.browserify !== "undefined" && !parserOptions.browserify)
- return;
-
- parser.plugin("call require", (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", expr.callee.range);
- dep.loc = expr.loc;
- if(parser.state.current.dependencies.length > 1) {
- const last = parser.state.current.dependencies[parser.state.current.dependencies.length - 1];
- if(last.critical && last.request === "." && last.userRequest === "." && last.recursive)
- parser.state.current.dependencies.pop();
- }
- parser.state.current.addDependency(dep);
- return true;
- });
- });
-
- params.normalModuleFactory.plugin("after-resolve", (data, done) => {
- // if this is a json file and there are no loaders active, we use the json-loader in order to avoid parse errors
- // @see https://github.com/webpack/webpack/issues/3363
- if(matchJson.test(data.request) && data.loaders.length === 0) {
- data.loaders.push({
- loader: jsonLoaderPath
- });
- }
- done(null, data);
- });
- });
- }
-}
-module.exports = CompatibilityPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const ConstDependency = require("./dependencies/ConstDependency"); + +const NullFactory = require("./NullFactory"); + +/** @typedef {import("./Compiler")} Compiler */ + +class CompatibilityPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler Webpack Compiler + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "CompatibilityPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set(ConstDependency, new NullFactory()); + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("CompatibilityPlugin", (parser, parserOptions) => { + if ( + parserOptions.browserify !== undefined && + !parserOptions.browserify + ) + return; + + parser.hooks.call + .for("require") + .tap("CompatibilityPlugin", 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", expr.callee.range); + dep.loc = expr.loc; + if (parser.state.current.dependencies.length > 1) { + 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.current.addDependency(dep); + return true; + }); + }); + } + ); + } +} +module.exports = CompatibilityPlugin; diff --git a/node_modules/webpack/lib/Compilation.js b/node_modules/webpack/lib/Compilation.js index 05f5be60d..a420da696 100644 --- a/node_modules/webpack/lib/Compilation.js +++ b/node_modules/webpack/lib/Compilation.js @@ -1,1455 +1,2513 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
- */
-"use strict";
-
-const asyncLib = require("async");
-const crypto = require("crypto");
-const Tapable = require("tapable");
-const EntryModuleNotFoundError = require("./EntryModuleNotFoundError");
-const ModuleNotFoundError = require("./ModuleNotFoundError");
-const ModuleDependencyWarning = require("./ModuleDependencyWarning");
-const ModuleDependencyError = require("./ModuleDependencyError");
-const Module = require("./Module");
-const Chunk = require("./Chunk");
-const Entrypoint = require("./Entrypoint");
-const MainTemplate = require("./MainTemplate");
-const ChunkTemplate = require("./ChunkTemplate");
-const HotUpdateChunkTemplate = require("./HotUpdateChunkTemplate");
-const ModuleTemplate = require("./ModuleTemplate");
-const Dependency = require("./Dependency");
-const ChunkRenderError = require("./ChunkRenderError");
-const AsyncDependencyToInitialChunkWarning = require("./AsyncDependencyToInitialChunkWarning");
-const CachedSource = require("webpack-sources").CachedSource;
-const Stats = require("./Stats");
-const Semaphore = require("./util/Semaphore");
-const Queue = require("./util/Queue");
-
-function byId(a, b) {
- if(a.id < b.id) return -1;
- if(a.id > b.id) return 1;
- return 0;
-}
-
-function iterationBlockVariable(variables, fn) {
- for(let indexVariable = 0; indexVariable < variables.length; indexVariable++) {
- let varDep = variables[indexVariable].dependencies;
- for(let indexVDep = 0; indexVDep < varDep.length; indexVDep++) {
- fn(varDep[indexVDep]);
- }
- }
-}
-
-function iterationOfArrayCallback(arr, fn) {
- for(let index = 0; index < arr.length; index++) {
- fn(arr[index]);
- }
-}
-
-class Compilation extends Tapable {
- constructor(compiler) {
- super();
- this.compiler = compiler;
- this.resolvers = compiler.resolvers;
- this.inputFileSystem = compiler.inputFileSystem;
-
- const options = this.options = compiler.options;
- this.outputOptions = options && options.output;
- this.bail = options && options.bail;
- this.profile = options && options.profile;
- this.performance = options && options.performance;
-
- this.mainTemplate = new MainTemplate(this.outputOptions);
- this.chunkTemplate = new ChunkTemplate(this.outputOptions);
- this.hotUpdateChunkTemplate = new HotUpdateChunkTemplate(this.outputOptions);
- this.moduleTemplate = new ModuleTemplate(this.outputOptions);
-
- this.semaphore = new Semaphore(options.parallelism || 100);
-
- this.entries = [];
- this.preparedChunks = [];
- this.entrypoints = {};
- this.chunks = [];
- this.namedChunks = {};
- this.modules = [];
- this._modules = {};
- this.cache = null;
- this.records = null;
- this.nextFreeModuleIndex = undefined;
- this.nextFreeModuleIndex2 = undefined;
- this.additionalChunkAssets = [];
- this.assets = {};
- this.errors = [];
- this.warnings = [];
- this.children = [];
- this.dependencyFactories = new Map();
- this.dependencyTemplates = new Map();
- this.dependencyTemplates.set("hash", "");
- this.childrenCounters = {};
- }
-
- getStats() {
- return new Stats(this);
- }
-
- templatesPlugin(name, fn) {
- this.mainTemplate.plugin(name, fn);
- this.chunkTemplate.plugin(name, fn);
- }
-
- addModule(module, cacheGroup) {
- const identifier = module.identifier();
- if(this._modules[identifier]) {
- return false;
- }
- const cacheName = (cacheGroup || "m") + identifier;
- if(this.cache && this.cache[cacheName]) {
- const cacheModule = this.cache[cacheName];
-
- let rebuild = true;
- if(!cacheModule.error && cacheModule.cacheable && this.fileTimestamps && this.contextTimestamps) {
- rebuild = cacheModule.needRebuild(this.fileTimestamps, this.contextTimestamps);
- }
-
- if(!rebuild) {
- cacheModule.disconnect();
- this._modules[identifier] = cacheModule;
- this.modules.push(cacheModule);
- cacheModule.errors.forEach(err => this.errors.push(err), this);
- cacheModule.warnings.forEach(err => this.warnings.push(err), this);
- return cacheModule;
- }
- }
- module.unbuild();
- this._modules[identifier] = module;
- if(this.cache) {
- this.cache[cacheName] = module;
- }
- this.modules.push(module);
- return true;
- }
-
- getModule(module) {
- const identifier = module.identifier();
- return this._modules[identifier];
- }
-
- findModule(identifier) {
- return this._modules[identifier];
- }
-
- buildModule(module, optional, origin, dependencies, thisCallback) {
- this.applyPlugins1("build-module", module);
- if(module.building) return module.building.push(thisCallback);
- const building = module.building = [thisCallback];
-
- function callback(err) {
- module.building = undefined;
- building.forEach(cb => cb(err));
- }
- module.build(this.options, this, this.resolvers.normal, this.inputFileSystem, (error) => {
- const errors = module.errors;
- for(let indexError = 0; indexError < errors.length; indexError++) {
- const err = errors[indexError];
- err.origin = origin;
- err.dependencies = dependencies;
- if(optional)
- this.warnings.push(err);
- else
- this.errors.push(err);
- }
-
- const warnings = module.warnings;
- for(let indexWarning = 0; indexWarning < warnings.length; indexWarning++) {
- const war = warnings[indexWarning];
- war.origin = origin;
- war.dependencies = dependencies;
- this.warnings.push(war);
- }
- module.dependencies.sort(Dependency.compare);
- if(error) {
- this.applyPlugins2("failed-module", module, error);
- return callback(error);
- }
- this.applyPlugins1("succeed-module", module);
- return callback();
- });
- }
-
- processModuleDependencies(module, callback) {
- const dependencies = [];
-
- function addDependency(dep) {
- for(let i = 0; i < dependencies.length; i++) {
- if(dep.isEqualResource(dependencies[i][0])) {
- return dependencies[i].push(dep);
- }
- }
- dependencies.push([dep]);
- }
-
- function addDependenciesBlock(block) {
- if(block.dependencies) {
- iterationOfArrayCallback(block.dependencies, addDependency);
- }
- if(block.blocks) {
- iterationOfArrayCallback(block.blocks, addDependenciesBlock);
- }
- if(block.variables) {
- iterationBlockVariable(block.variables, addDependency);
- }
- }
- addDependenciesBlock(module);
- this.addModuleDependencies(module, dependencies, this.bail, null, true, callback);
- }
-
- addModuleDependencies(module, dependencies, bail, cacheGroup, recursive, callback) {
- let _this = this;
- const start = _this.profile && Date.now();
-
- const factories = [];
- for(let i = 0; i < dependencies.length; i++) {
- const factory = _this.dependencyFactories.get(dependencies[i][0].constructor);
- if(!factory) {
- return callback(new Error(`No module factory available for dependency type: ${dependencies[i][0].constructor.name}`));
- }
- factories[i] = [factory, dependencies[i]];
- }
- asyncLib.forEach(factories, function iteratorFactory(item, callback) {
- const dependencies = item[1];
-
- const errorAndCallback = function errorAndCallback(err) {
- err.origin = module;
- _this.errors.push(err);
- if(bail) {
- callback(err);
- } else {
- callback();
- }
- };
- const warningAndCallback = function warningAndCallback(err) {
- err.origin = module;
- _this.warnings.push(err);
- callback();
- };
-
- const semaphore = _this.semaphore;
- semaphore.acquire(() => {
- if(_this === null) return semaphore.release();
-
- const factory = item[0];
- factory.create({
- contextInfo: {
- issuer: module.nameForCondition && module.nameForCondition(),
- compiler: _this.compiler.name
- },
- context: module.context,
- dependencies: dependencies
- }, function factoryCallback(err, dependentModule) {
- if(_this === null) return semaphore.release();
-
- let afterFactory;
-
- function isOptional() {
- return dependencies.filter(d => !d.optional).length === 0;
- }
-
- function errorOrWarningAndCallback(err) {
- if(isOptional()) {
- return warningAndCallback(err);
- } else {
- return errorAndCallback(err);
- }
- }
-
- function iterationDependencies(depend) {
- for(let index = 0; index < depend.length; index++) {
- const dep = depend[index];
- dep.module = dependentModule;
- dependentModule.addReason(module, dep);
- }
- }
-
- if(err) {
- semaphore.release();
- return errorOrWarningAndCallback(new ModuleNotFoundError(module, err, dependencies));
- }
- if(!dependentModule) {
- semaphore.release();
- return process.nextTick(callback);
- }
- if(_this.profile) {
- if(!dependentModule.profile) {
- dependentModule.profile = {};
- }
- afterFactory = Date.now();
- dependentModule.profile.factory = afterFactory - start;
- }
-
- dependentModule.issuer = module;
- const newModule = _this.addModule(dependentModule, cacheGroup);
-
- if(!newModule) { // from cache
- dependentModule = _this.getModule(dependentModule);
-
- if(dependentModule.optional) {
- dependentModule.optional = isOptional();
- }
-
- iterationDependencies(dependencies);
-
- if(_this.profile) {
- if(!module.profile) {
- module.profile = {};
- }
- const time = Date.now() - start;
- if(!module.profile.dependencies || time > module.profile.dependencies) {
- module.profile.dependencies = time;
- }
- }
-
- semaphore.release();
- return process.nextTick(callback);
- }
-
- if(newModule instanceof Module) {
- if(_this.profile) {
- newModule.profile = dependentModule.profile;
- }
-
- newModule.optional = isOptional();
- newModule.issuer = dependentModule.issuer;
- dependentModule = newModule;
-
- iterationDependencies(dependencies);
-
- if(_this.profile) {
- const afterBuilding = Date.now();
- module.profile.building = afterBuilding - afterFactory;
- }
-
- semaphore.release();
- if(recursive) {
- return process.nextTick(_this.processModuleDependencies.bind(_this, dependentModule, callback));
- } else {
- return process.nextTick(callback);
- }
- }
-
- dependentModule.optional = isOptional();
-
- iterationDependencies(dependencies);
-
- _this.buildModule(dependentModule, isOptional(), module, dependencies, err => {
- if(_this === null) return semaphore.release();
-
- if(err) {
- semaphore.release();
- return errorOrWarningAndCallback(err);
- }
-
- if(_this.profile) {
- const afterBuilding = Date.now();
- dependentModule.profile.building = afterBuilding - afterFactory;
- }
-
- semaphore.release();
- if(recursive) {
- _this.processModuleDependencies(dependentModule, callback);
- } else {
- return callback();
- }
- });
-
- });
- });
- }, function finalCallbackAddModuleDependencies(err) {
- // In V8, the Error objects keep a reference to the functions on the stack. These warnings &
- // errors are created inside closures that keep a reference to the Compilation, so errors are
- // leaking the Compilation object. Setting _this to null workarounds the following issue in V8.
- // https://bugs.chromium.org/p/chromium/issues/detail?id=612191
- _this = null;
-
- if(err) {
- return callback(err);
- }
-
- return process.nextTick(callback);
- });
- }
-
- _addModuleChain(context, dependency, onModule, callback) {
- const start = this.profile && Date.now();
-
- const errorAndCallback = this.bail ? (err) => {
- callback(err);
- } : (err) => {
- err.dependencies = [dependency];
- this.errors.push(err);
- callback();
- };
-
- if(typeof dependency !== "object" || dependency === null || !dependency.constructor) {
- throw new Error("Parameter 'dependency' must be a Dependency");
- }
-
- const moduleFactory = this.dependencyFactories.get(dependency.constructor);
- if(!moduleFactory) {
- throw new Error(`No dependency factory available for this dependency type: ${dependency.constructor.name}`);
- }
-
- this.semaphore.acquire(() => {
- moduleFactory.create({
- contextInfo: {
- issuer: "",
- compiler: this.compiler.name
- },
- context: context,
- dependencies: [dependency]
- }, (err, module) => {
- if(err) {
- this.semaphore.release();
- return errorAndCallback(new EntryModuleNotFoundError(err));
- }
-
- let afterFactory;
-
- if(this.profile) {
- if(!module.profile) {
- module.profile = {};
- }
- afterFactory = Date.now();
- module.profile.factory = afterFactory - start;
- }
-
- const result = this.addModule(module);
- if(!result) {
- module = this.getModule(module);
-
- onModule(module);
-
- if(this.profile) {
- const afterBuilding = Date.now();
- module.profile.building = afterBuilding - afterFactory;
- }
-
- this.semaphore.release();
- return callback(null, module);
- }
-
- if(result instanceof Module) {
- if(this.profile) {
- result.profile = module.profile;
- }
-
- module = result;
-
- onModule(module);
-
- moduleReady.call(this);
- return;
- }
-
- onModule(module);
-
- this.buildModule(module, false, null, null, (err) => {
- if(err) {
- this.semaphore.release();
- return errorAndCallback(err);
- }
-
- if(this.profile) {
- const afterBuilding = Date.now();
- module.profile.building = afterBuilding - afterFactory;
- }
-
- moduleReady.call(this);
- });
-
- function moduleReady() {
- this.semaphore.release();
- this.processModuleDependencies(module, err => {
- if(err) {
- return callback(err);
- }
-
- return callback(null, module);
- });
- }
- });
- });
- }
-
- addEntry(context, entry, name, callback) {
- const slot = {
- name: name,
- module: null
- };
- this.preparedChunks.push(slot);
- this._addModuleChain(context, entry, (module) => {
-
- entry.module = module;
- this.entries.push(module);
- module.issuer = null;
-
- }, (err, module) => {
- if(err) {
- return callback(err);
- }
-
- if(module) {
- slot.module = module;
- } else {
- const idx = this.preparedChunks.indexOf(slot);
- this.preparedChunks.splice(idx, 1);
- }
- return callback(null, module);
- });
- }
-
- prefetch(context, dependency, callback) {
- this._addModuleChain(context, dependency, module => {
-
- module.prefetched = true;
- module.issuer = null;
-
- }, callback);
- }
-
- rebuildModule(module, thisCallback) {
- if(module.variables.length || module.blocks.length)
- throw new Error("Cannot rebuild a complex module with variables or blocks");
- if(module.rebuilding) {
- return module.rebuilding.push(thisCallback);
- }
- const rebuilding = module.rebuilding = [thisCallback];
-
- function callback(err) {
- module.rebuilding = undefined;
- rebuilding.forEach(cb => cb(err));
- }
- const deps = module.dependencies.slice();
- this.buildModule(module, false, module, null, (err) => {
- if(err) return callback(err);
-
- this.processModuleDependencies(module, (err) => {
- if(err) return callback(err);
- deps.forEach(d => {
- if(d.module && d.module.removeReason(module, d)) {
- module.forEachChunk(chunk => {
- if(!d.module.hasReasonForChunk(chunk)) {
- if(d.module.removeChunk(chunk)) {
- this.removeChunkFromDependencies(d.module, chunk);
- }
- }
- });
- }
- });
- callback();
- });
-
- });
- }
-
- finish() {
- const modules = this.modules;
- this.applyPlugins1("finish-modules", modules);
-
- for(let index = 0; index < modules.length; index++) {
- const module = modules[index];
- this.reportDependencyErrorsAndWarnings(module, [module]);
- }
- }
-
- unseal() {
- this.applyPlugins0("unseal");
- this.chunks.length = 0;
- this.namedChunks = {};
- this.additionalChunkAssets.length = 0;
- this.assets = {};
- this.modules.forEach(module => module.unseal());
- }
-
- seal(callback) {
- const self = this;
- self.applyPlugins0("seal");
- self.nextFreeModuleIndex = 0;
- self.nextFreeModuleIndex2 = 0;
- self.preparedChunks.forEach(preparedChunk => {
- const module = preparedChunk.module;
- const chunk = self.addChunk(preparedChunk.name, module);
- const entrypoint = self.entrypoints[chunk.name] = new Entrypoint(chunk.name);
- entrypoint.unshiftChunk(chunk);
-
- chunk.addModule(module);
- module.addChunk(chunk);
- chunk.entryModule = module;
- self.assignIndex(module);
- self.assignDepth(module);
- });
- self.processDependenciesBlocksForChunks(self.chunks.slice());
- self.sortModules(self.modules);
- self.applyPlugins0("optimize");
-
- while(self.applyPluginsBailResult1("optimize-modules-basic", self.modules) ||
- self.applyPluginsBailResult1("optimize-modules", self.modules) ||
- self.applyPluginsBailResult1("optimize-modules-advanced", self.modules)) { /* empty */ }
- self.applyPlugins1("after-optimize-modules", self.modules);
-
- while(self.applyPluginsBailResult1("optimize-chunks-basic", self.chunks) ||
- self.applyPluginsBailResult1("optimize-chunks", self.chunks) ||
- self.applyPluginsBailResult1("optimize-chunks-advanced", self.chunks)) { /* empty */ }
- self.applyPlugins1("after-optimize-chunks", self.chunks);
-
- self.applyPluginsAsyncSeries("optimize-tree", self.chunks, self.modules, function sealPart2(err) {
- if(err) {
- return callback(err);
- }
-
- self.applyPlugins2("after-optimize-tree", self.chunks, self.modules);
-
- while(self.applyPluginsBailResult("optimize-chunk-modules-basic", self.chunks, self.modules) ||
- self.applyPluginsBailResult("optimize-chunk-modules", self.chunks, self.modules) ||
- self.applyPluginsBailResult("optimize-chunk-modules-advanced", self.chunks, self.modules)) { /* empty */ }
- self.applyPlugins2("after-optimize-chunk-modules", self.chunks, self.modules);
-
- const shouldRecord = self.applyPluginsBailResult("should-record") !== false;
-
- self.applyPlugins2("revive-modules", self.modules, self.records);
- self.applyPlugins1("optimize-module-order", self.modules);
- self.applyPlugins1("advanced-optimize-module-order", self.modules);
- self.applyPlugins1("before-module-ids", self.modules);
- self.applyPlugins1("module-ids", self.modules);
- self.applyModuleIds();
- self.applyPlugins1("optimize-module-ids", self.modules);
- self.applyPlugins1("after-optimize-module-ids", self.modules);
-
- self.sortItemsWithModuleIds();
-
- self.applyPlugins2("revive-chunks", self.chunks, self.records);
- self.applyPlugins1("optimize-chunk-order", self.chunks);
- self.applyPlugins1("before-chunk-ids", self.chunks);
- self.applyChunkIds();
- self.applyPlugins1("optimize-chunk-ids", self.chunks);
- self.applyPlugins1("after-optimize-chunk-ids", self.chunks);
-
- self.sortItemsWithChunkIds();
-
- if(shouldRecord)
- self.applyPlugins2("record-modules", self.modules, self.records);
- if(shouldRecord)
- self.applyPlugins2("record-chunks", self.chunks, self.records);
-
- self.applyPlugins0("before-hash");
- self.createHash();
- self.applyPlugins0("after-hash");
-
- if(shouldRecord)
- self.applyPlugins1("record-hash", self.records);
-
- self.applyPlugins0("before-module-assets");
- self.createModuleAssets();
- if(self.applyPluginsBailResult("should-generate-chunk-assets") !== false) {
- self.applyPlugins0("before-chunk-assets");
- self.createChunkAssets();
- }
- self.applyPlugins1("additional-chunk-assets", self.chunks);
- self.summarizeDependencies();
- if(shouldRecord)
- self.applyPlugins2("record", self, self.records);
-
- self.applyPluginsAsync("additional-assets", err => {
- if(err) {
- return callback(err);
- }
- self.applyPluginsAsync("optimize-chunk-assets", self.chunks, err => {
- if(err) {
- return callback(err);
- }
- self.applyPlugins1("after-optimize-chunk-assets", self.chunks);
- self.applyPluginsAsync("optimize-assets", self.assets, err => {
- if(err) {
- return callback(err);
- }
- self.applyPlugins1("after-optimize-assets", self.assets);
- if(self.applyPluginsBailResult("need-additional-seal")) {
- self.unseal();
- return self.seal(callback);
- }
- return self.applyPluginsAsync("after-seal", callback);
- });
- });
- });
- });
- }
-
- sortModules(modules) {
- modules.sort((a, b) => {
- if(a.index < b.index) return -1;
- if(a.index > b.index) return 1;
- return 0;
- });
- }
-
- reportDependencyErrorsAndWarnings(module, blocks) {
- for(let indexBlock = 0; indexBlock < blocks.length; indexBlock++) {
- const block = blocks[indexBlock];
- const dependencies = block.dependencies;
-
- for(let indexDep = 0; indexDep < dependencies.length; indexDep++) {
- const d = dependencies[indexDep];
-
- const warnings = d.getWarnings();
- if(warnings) {
- for(let indexWar = 0; indexWar < warnings.length; indexWar++) {
- const w = warnings[indexWar];
-
- const warning = new ModuleDependencyWarning(module, w, d.loc);
- this.warnings.push(warning);
- }
- }
- const errors = d.getErrors();
- if(errors) {
- for(let indexErr = 0; indexErr < errors.length; indexErr++) {
- const e = errors[indexErr];
-
- const error = new ModuleDependencyError(module, e, d.loc);
- this.errors.push(error);
- }
- }
- }
-
- this.reportDependencyErrorsAndWarnings(module, block.blocks);
- }
- }
-
- addChunk(name, module, loc) {
- if(name) {
- if(Object.prototype.hasOwnProperty.call(this.namedChunks, name)) {
- const chunk = this.namedChunks[name];
- if(module) {
- chunk.addOrigin(module, loc);
- }
- return chunk;
- }
- }
- const chunk = new Chunk(name, module, loc);
- this.chunks.push(chunk);
- if(name) {
- this.namedChunks[name] = chunk;
- }
- return chunk;
- }
-
- assignIndex(module) {
- const _this = this;
-
- const queue = [() => {
- assignIndexToModule(module);
- }];
-
- const iteratorAllDependencies = d => {
- queue.push(() => assignIndexToDependency(d));
- };
-
- function assignIndexToModule(module) {
- // enter module
- if(typeof module.index !== "number") {
- module.index = _this.nextFreeModuleIndex++;
-
- // leave module
- queue.push(() => module.index2 = _this.nextFreeModuleIndex2++);
-
- // enter it as block
- assignIndexToDependencyBlock(module);
- }
- }
-
- function assignIndexToDependency(dependency) {
- if(dependency.module) {
- queue.push(() => assignIndexToModule(dependency.module));
- }
- }
-
- function assignIndexToDependencyBlock(block) {
- let allDependencies = [];
-
- function iteratorDependency(d) {
- allDependencies.push(d);
- }
-
- function iteratorBlock(b) {
- queue.push(() => assignIndexToDependencyBlock(b));
- }
-
- if(block.variables) {
- iterationBlockVariable(block.variables, iteratorDependency);
- }
-
- if(block.dependencies) {
- iterationOfArrayCallback(block.dependencies, iteratorDependency);
- }
- if(block.blocks) {
- const blocks = block.blocks;
- let indexBlock = blocks.length;
- while(indexBlock--) {
- iteratorBlock(blocks[indexBlock]);
- }
- }
-
- let indexAll = allDependencies.length;
- while(indexAll--) {
- iteratorAllDependencies(allDependencies[indexAll]);
- }
- }
-
- while(queue.length) {
- queue.pop()();
- }
- }
-
- assignDepth(module) {
- function assignDepthToModule(module, depth) {
- // enter module
- if(typeof module.depth === "number" && module.depth <= depth) return;
- module.depth = depth;
-
- // enter it as block
- assignDepthToDependencyBlock(module, depth + 1);
- }
-
- function assignDepthToDependency(dependency, depth) {
- if(dependency.module) {
- queue.push(() => assignDepthToModule(dependency.module, depth));
- }
- }
-
- function assignDepthToDependencyBlock(block, depth) {
- function iteratorDependency(d) {
- assignDepthToDependency(d, depth);
- }
-
- function iteratorBlock(b) {
- assignDepthToDependencyBlock(b, depth);
- }
-
- if(block.variables) {
- iterationBlockVariable(block.variables, iteratorDependency);
- }
-
- if(block.dependencies) {
- iterationOfArrayCallback(block.dependencies, iteratorDependency);
- }
-
- if(block.blocks) {
- iterationOfArrayCallback(block.blocks, iteratorBlock);
- }
- }
-
- const queue = [() => {
- assignDepthToModule(module, 0);
- }];
- while(queue.length) {
- queue.pop()();
- }
- }
-
- // This method creates the Chunk graph from the Module graph
- processDependenciesBlocksForChunks(inputChunks) {
- // Process is splitting into two parts:
- // Part one traverse the module graph and builds a very basic chunks graph
- // in chunkDependencies.
- // Part two traverse every possible way through the basic chunk graph and
- // tracks the available modules. While traversing it connects chunks with
- // eachother and Blocks with Chunks. It stops traversing when all modules
- // for a chunk are already available. So it doesn't connect unneeded chunks.
-
- const chunkDependencies = new Map(); // Map<Chunk, Array<{Module, Chunk}>>
- const allCreatedChunks = new Set();
-
- // PART ONE
-
- const blockChunks = new Map();
-
- // Start with the provided modules/chunks
- const queue = inputChunks.map(chunk => ({
- block: chunk.entryModule,
- chunk: chunk
- }));
-
- let block, chunk;
-
- // For each async Block in graph
- const iteratorBlock = b => {
- // 1. We create a chunk for this Block
- // but only once (blockChunks map)
- let c = blockChunks.get(b);
- if(c === undefined) {
- c = this.namedChunks[b.chunkName];
- if(c && c.isInitial()) {
- // TODO webpack 4: convert this to an error
- this.warnings.push(new AsyncDependencyToInitialChunkWarning(b.chunkName, b.module, b.loc));
- c = chunk;
- } else {
- c = this.addChunk(b.chunkName, b.module, b.loc);
- blockChunks.set(b, c);
- allCreatedChunks.add(c);
- // We initialize the chunks property
- // this is later filled with the chunk when needed
- b.chunks = [];
- }
- }
-
- // 2. We store the Block+Chunk mapping as dependency for the chunk
- let deps = chunkDependencies.get(chunk);
- if(!deps) chunkDependencies.set(chunk, deps = []);
- deps.push({
- block: b,
- chunk: c
- });
-
- // 3. We enqueue the DependenciesBlock for traversal
- queue.push({
- block: b,
- chunk: c
- });
- };
-
- // For each Dependency in the graph
- const iteratorDependency = d => {
- // We skip Dependencies without Module pointer
- if(!d.module) {
- return;
- }
- // We skip weak Dependencies
- if(d.weak) {
- return;
- }
- // We connect Module and Chunk when not already done
- if(chunk.addModule(d.module)) {
- d.module.addChunk(chunk);
-
- // And enqueue the Module for traversal
- queue.push({
- block: d.module,
- chunk
- });
- }
- };
-
- // Iterative traversal of the Module graph
- // Recursive would be simpler to write but could result in Stack Overflows
- while(queue.length) {
- const queueItem = queue.pop();
- block = queueItem.block;
- chunk = queueItem.chunk;
-
- // Traverse all variables, Dependencies and Blocks
- if(block.variables) {
- iterationBlockVariable(block.variables, iteratorDependency);
- }
-
- if(block.dependencies) {
- iterationOfArrayCallback(block.dependencies, iteratorDependency);
- }
-
- if(block.blocks) {
- iterationOfArrayCallback(block.blocks, iteratorBlock);
- }
- }
-
- // PART TWO
-
- let availableModules;
- let newAvailableModules;
- const queue2 = new Queue(inputChunks.map(chunk => ({
- chunk,
- availableModules: new Set()
- })));
-
- // Helper function to check if all modules of a chunk are available
- const areModulesAvailable = (chunk, availableModules) => {
- for(const module of chunk.modulesIterable) {
- if(!availableModules.has(module))
- return false;
- }
- return true;
- };
-
- // For each edge in the basic chunk graph
- const filterFn = dep => {
- // Filter egdes that are not needed because all modules are already available
- // This also filters circular dependencies in the chunks graph
- const depChunk = dep.chunk;
- if(areModulesAvailable(depChunk, newAvailableModules))
- return false; // break all modules are already available
- return true;
- };
-
- const minAvailableModulesMap = new Map();
-
- // Iterative traversing of the basic chunk graph
- while(queue2.length) {
- const queueItem = queue2.dequeue();
- chunk = queueItem.chunk;
- availableModules = queueItem.availableModules;
-
- // 1. Get minimal available modules
- // It doesn't make sense to traverse a chunk again with more available modules.
- // This step calculates the minimal available modules and skips traversal when
- // the list didn't shrink.
- let minAvailableModules = minAvailableModulesMap.get(chunk);
- if(minAvailableModules === undefined) {
- minAvailableModulesMap.set(chunk, new Set(availableModules));
- } else {
- let deletedModules = false;
- for(const m of minAvailableModules) {
- if(!availableModules.has(m)) {
- minAvailableModules.delete(m);
- deletedModules = true;
- }
- }
- if(!deletedModules)
- continue;
- availableModules = minAvailableModules;
- }
-
- // 2. Get the edges at this point of the graph
- const deps = chunkDependencies.get(chunk);
- if(!deps) continue;
- if(deps.length === 0) continue;
-
- // 3. Create a new Set of available modules at this points
- newAvailableModules = new Set(availableModules);
- for(const m of chunk.modulesIterable)
- newAvailableModules.add(m);
-
- // 4. Filter edges with available modules
- const filteredDeps = deps.filter(filterFn);
-
- // 5. Foreach remaining edge
- const nextChunks = new Set();
- for(let i = 0; i < filteredDeps.length; i++) {
- const dep = filteredDeps[i];
- const depChunk = dep.chunk;
- const depBlock = dep.block;
-
- // 6. Connnect block with chunk
- if(depChunk.addBlock(depBlock)) {
- depBlock.chunks.push(depChunk);
- }
-
- // 7. Connect chunk with parent
- if(chunk.addChunk(depChunk)) {
- depChunk.addParent(chunk);
- }
-
- nextChunks.add(depChunk);
- }
-
- // 8. Enqueue further traversal
- for(const nextChunk of nextChunks) {
- queue2.enqueue({
- chunk: nextChunk,
- availableModules: newAvailableModules
- });
- }
- }
-
- // Remove all unconnected chunks
- for(const chunk of allCreatedChunks) {
- if(chunk.parents.length === 0)
- chunk.remove("unconnected");
- }
- }
-
- removeChunkFromDependencies(block, chunk) {
- const iteratorDependency = d => {
- if(!d.module) {
- return;
- }
- if(!d.module.hasReasonForChunk(chunk)) {
- if(d.module.removeChunk(chunk)) {
- this.removeChunkFromDependencies(d.module, chunk);
- }
- }
- };
-
- const blocks = block.blocks;
- for(let indexBlock = 0; indexBlock < blocks.length; indexBlock++) {
- const chunks = blocks[indexBlock].chunks;
- for(let indexChunk = 0; indexChunk < chunks.length; indexChunk++) {
- const blockChunk = chunks[indexChunk];
- chunk.removeChunk(blockChunk);
- blockChunk.removeParent(chunk);
- this.removeChunkFromDependencies(chunks, blockChunk);
- }
- }
-
- if(block.dependencies) {
- iterationOfArrayCallback(block.dependencies, iteratorDependency);
- }
-
- if(block.variables) {
- iterationBlockVariable(block.variables, iteratorDependency);
- }
- }
-
- applyModuleIds() {
- let unusedIds = [];
- let nextFreeModuleId = 0;
- let usedIds = [];
- // TODO consider Map when performance has improved https://gist.github.com/sokra/234c077e1299b7369461f1708519c392
- const usedIdMap = Object.create(null);
- if(this.usedModuleIds) {
- Object.keys(this.usedModuleIds).forEach(key => {
- const id = this.usedModuleIds[key];
- if(!usedIdMap[id]) {
- usedIds.push(id);
- usedIdMap[id] = true;
- }
- });
- }
-
- const modules1 = this.modules;
- for(let indexModule1 = 0; indexModule1 < modules1.length; indexModule1++) {
- const module1 = modules1[indexModule1];
- if(module1.id && !usedIdMap[module1.id]) {
- usedIds.push(module1.id);
- usedIdMap[module1.id] = true;
- }
- }
-
- if(usedIds.length > 0) {
- let usedIdMax = -1;
- for(let index = 0; index < usedIds.length; index++) {
- const usedIdKey = usedIds[index];
-
- if(typeof usedIdKey !== "number") {
- continue;
- }
-
- usedIdMax = Math.max(usedIdMax, usedIdKey);
- }
-
- let lengthFreeModules = nextFreeModuleId = usedIdMax + 1;
-
- while(lengthFreeModules--) {
- if(!usedIdMap[lengthFreeModules]) {
- unusedIds.push(lengthFreeModules);
- }
- }
- }
-
- const modules2 = this.modules;
- for(let indexModule2 = 0; indexModule2 < modules2.length; indexModule2++) {
- const module2 = modules2[indexModule2];
- if(module2.id === null) {
- if(unusedIds.length > 0)
- module2.id = unusedIds.pop();
- else
- module2.id = nextFreeModuleId++;
- }
- }
- }
-
- applyChunkIds() {
- const unusedIds = [];
- let nextFreeChunkId = 0;
-
- function getNextFreeChunkId(usedChunkIds) {
- const keyChunks = Object.keys(usedChunkIds);
- let result = -1;
-
- for(let index = 0; index < keyChunks.length; index++) {
- const usedIdKey = keyChunks[index];
- const usedIdValue = usedChunkIds[usedIdKey];
-
- if(typeof usedIdValue !== "number") {
- continue;
- }
-
- result = Math.max(result, usedIdValue);
- }
-
- return result;
- }
-
- if(this.usedChunkIds) {
- nextFreeChunkId = getNextFreeChunkId(this.usedChunkIds) + 1;
- let index = nextFreeChunkId;
- while(index--) {
- if(this.usedChunkIds[index] !== index) {
- unusedIds.push(index);
- }
- }
- }
-
- const chunks = this.chunks;
- for(let indexChunk = 0; indexChunk < chunks.length; indexChunk++) {
- const chunk = chunks[indexChunk];
- if(chunk.id === null) {
- if(unusedIds.length > 0)
- chunk.id = unusedIds.pop();
- else
- chunk.id = nextFreeChunkId++;
- }
- if(!chunk.ids) {
- chunk.ids = [chunk.id];
- }
- }
- }
-
- sortItemsWithModuleIds() {
- this.modules.sort(byId);
-
- const modules = this.modules;
- for(let indexModule = 0; indexModule < modules.length; indexModule++) {
- modules[indexModule].sortItems(false);
- }
-
- const chunks = this.chunks;
- for(let indexChunk = 0; indexChunk < chunks.length; indexChunk++) {
- chunks[indexChunk].sortItems();
- }
- }
-
- sortItemsWithChunkIds() {
- this.chunks.sort(byId);
-
- const modules = this.modules;
- for(let indexModule = 0; indexModule < modules.length; indexModule++) {
- modules[indexModule].sortItems(true);
- }
-
- const chunks = this.chunks;
- for(let indexChunk = 0; indexChunk < chunks.length; indexChunk++) {
- chunks[indexChunk].sortItems();
- }
-
- const byMessage = (a, b) => {
- const ma = `${a.message}`;
- const mb = `${b.message}`;
- if(ma < mb) return -1;
- if(mb < ma) return 1;
- return 0;
- };
-
- this.errors.sort(byMessage);
- this.warnings.sort(byMessage);
- }
-
- summarizeDependencies() {
- function filterDups(array) {
- const newArray = [];
- for(let i = 0; i < array.length; i++) {
- if(i === 0 || array[i - 1] !== array[i])
- newArray.push(array[i]);
- }
- return newArray;
- }
- this.fileDependencies = (this.compilationDependencies || []).slice();
- this.contextDependencies = [];
- this.missingDependencies = [];
-
- const children = this.children;
- for(let indexChildren = 0; indexChildren < children.length; indexChildren++) {
- const child = children[indexChildren];
-
- this.fileDependencies = this.fileDependencies.concat(child.fileDependencies);
- this.contextDependencies = this.contextDependencies.concat(child.contextDependencies);
- this.missingDependencies = this.missingDependencies.concat(child.missingDependencies);
- }
-
- const modules = this.modules;
- for(let indexModule = 0; indexModule < modules.length; indexModule++) {
- const module = modules[indexModule];
-
- if(module.fileDependencies) {
- const fileDependencies = module.fileDependencies;
- for(let indexFileDep = 0; indexFileDep < fileDependencies.length; indexFileDep++) {
- this.fileDependencies.push(fileDependencies[indexFileDep]);
- }
- }
- if(module.contextDependencies) {
- const contextDependencies = module.contextDependencies;
- for(let indexContextDep = 0; indexContextDep < contextDependencies.length; indexContextDep++) {
- this.contextDependencies.push(contextDependencies[indexContextDep]);
- }
- }
- }
- this.errors.forEach(error => {
- if(Array.isArray(error.missing)) {
- error.missing.forEach(item => this.missingDependencies.push(item));
- }
- });
- this.fileDependencies.sort();
- this.fileDependencies = filterDups(this.fileDependencies);
- this.contextDependencies.sort();
- this.contextDependencies = filterDups(this.contextDependencies);
- this.missingDependencies.sort();
- this.missingDependencies = filterDups(this.missingDependencies);
- }
-
- createHash() {
- const outputOptions = this.outputOptions;
- const hashFunction = outputOptions.hashFunction;
- const hashDigest = outputOptions.hashDigest;
- const hashDigestLength = outputOptions.hashDigestLength;
- const hash = crypto.createHash(hashFunction);
- if(outputOptions.hashSalt)
- hash.update(outputOptions.hashSalt);
- this.mainTemplate.updateHash(hash);
- this.chunkTemplate.updateHash(hash);
- this.moduleTemplate.updateHash(hash);
- this.children.forEach(function(child) {
- hash.update(child.hash);
- });
- this.warnings.forEach(function(warning) {
- hash.update(`${warning.message}`);
- });
- this.errors.forEach(function(error) {
- hash.update(`${error.message}`);
- });
- // clone needed as sort below is inplace mutation
- const chunks = this.chunks.slice();
- /**
- * sort here will bring all "falsy" values to the beginning
- * this is needed as the "hasRuntime()" chunks are dependent on the
- * hashes of the non-runtime chunks.
- */
- chunks.sort((a, b) => {
- const aEntry = a.hasRuntime();
- const bEntry = b.hasRuntime();
- if(aEntry && !bEntry) return 1;
- if(!aEntry && bEntry) return -1;
- return 0;
- });
- for(let i = 0; i < chunks.length; i++) {
- const chunk = chunks[i];
- const chunkHash = crypto.createHash(hashFunction);
- if(outputOptions.hashSalt)
- chunkHash.update(outputOptions.hashSalt);
- chunk.updateHash(chunkHash);
- if(chunk.hasRuntime()) {
- this.mainTemplate.updateHashForChunk(chunkHash, chunk);
- } else {
- this.chunkTemplate.updateHashForChunk(chunkHash, chunk);
- }
- this.applyPlugins2("chunk-hash", chunk, chunkHash);
- chunk.hash = chunkHash.digest(hashDigest);
- hash.update(chunk.hash);
- chunk.renderedHash = chunk.hash.substr(0, hashDigestLength);
- }
- this.fullHash = hash.digest(hashDigest);
- this.hash = this.fullHash.substr(0, hashDigestLength);
- }
-
- modifyHash(update) {
- const outputOptions = this.outputOptions;
- const hashFunction = outputOptions.hashFunction;
- const hashDigest = outputOptions.hashDigest;
- const hashDigestLength = outputOptions.hashDigestLength;
- const hash = crypto.createHash(hashFunction);
- hash.update(this.fullHash);
- hash.update(update);
- this.fullHash = hash.digest(hashDigest);
- this.hash = this.fullHash.substr(0, hashDigestLength);
- }
-
- createModuleAssets() {
- for(let i = 0; i < this.modules.length; i++) {
- const module = this.modules[i];
- if(module.assets) {
- Object.keys(module.assets).forEach((assetName) => {
- const fileName = this.getPath(assetName);
- this.assets[fileName] = module.assets[assetName];
- this.applyPlugins2("module-asset", module, fileName);
- });
- }
- }
- }
-
- createChunkAssets() {
- const outputOptions = this.outputOptions;
- const filename = outputOptions.filename;
- const chunkFilename = outputOptions.chunkFilename;
- for(let i = 0; i < this.chunks.length; i++) {
- const chunk = this.chunks[i];
- chunk.files = [];
- const chunkHash = chunk.hash;
- let source;
- let file;
- const filenameTemplate = chunk.filenameTemplate ? chunk.filenameTemplate :
- chunk.isInitial() ? filename :
- chunkFilename;
- try {
- const useChunkHash = !chunk.hasRuntime() || (this.mainTemplate.useChunkHash && this.mainTemplate.useChunkHash(chunk));
- const usedHash = useChunkHash ? chunkHash : this.fullHash;
- const cacheName = "c" + chunk.id;
- if(this.cache && this.cache[cacheName] && this.cache[cacheName].hash === usedHash) {
- source = this.cache[cacheName].source;
- } else {
- if(chunk.hasRuntime()) {
- source = this.mainTemplate.render(this.hash, chunk, this.moduleTemplate, this.dependencyTemplates);
- } else {
- source = this.chunkTemplate.render(chunk, this.moduleTemplate, this.dependencyTemplates);
- }
- if(this.cache) {
- this.cache[cacheName] = {
- hash: usedHash,
- source: source = (source instanceof CachedSource ? source : new CachedSource(source))
- };
- }
- }
- file = this.getPath(filenameTemplate, {
- noChunkHash: !useChunkHash,
- chunk
- });
- if(this.assets[file])
- throw new Error(`Conflict: Multiple assets emit to the same filename ${file}`);
- this.assets[file] = source;
- chunk.files.push(file);
- this.applyPlugins2("chunk-asset", chunk, file);
- } catch(err) {
- this.errors.push(new ChunkRenderError(chunk, file || filenameTemplate, err));
- }
- }
- }
-
- getPath(filename, data) {
- data = data || {};
- data.hash = data.hash || this.hash;
- return this.mainTemplate.applyPluginsWaterfall("asset-path", filename, data);
- }
-
- createChildCompiler(name, outputOptions, plugins) {
- const idx = (this.childrenCounters[name] || 0);
- this.childrenCounters[name] = idx + 1;
- return this.compiler.createChildCompiler(this, name, idx, outputOptions, plugins);
- }
-
- checkConstraints() {
- const usedIds = {};
-
- const modules = this.modules;
- for(let indexModule = 0; indexModule < modules.length; indexModule++) {
- const moduleId = modules[indexModule].id;
-
- if(usedIds[moduleId])
- throw new Error(`checkConstraints: duplicate module id ${moduleId}`);
- }
-
- const chunks = this.chunks;
- for(let indexChunk = 0; indexChunk < chunks.length; indexChunk++) {
- const chunk = chunks[indexChunk];
-
- if(chunks.indexOf(chunk) !== indexChunk)
- throw new Error(`checkConstraints: duplicate chunk in compilation ${chunk.debugId}`);
- chunk.checkConstraints();
- }
- }
-}
-
-module.exports = Compilation;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra + */ +"use strict"; + +const asyncLib = require("neo-async"); +const util = require("util"); +const { CachedSource } = require("webpack-sources"); +const { + Tapable, + SyncHook, + SyncBailHook, + SyncWaterfallHook, + AsyncSeriesHook +} = require("tapable"); +const EntryModuleNotFoundError = require("./EntryModuleNotFoundError"); +const ModuleNotFoundError = require("./ModuleNotFoundError"); +const ModuleDependencyWarning = require("./ModuleDependencyWarning"); +const ModuleDependencyError = require("./ModuleDependencyError"); +const ChunkGroup = require("./ChunkGroup"); +const Chunk = require("./Chunk"); +const Entrypoint = require("./Entrypoint"); +const MainTemplate = require("./MainTemplate"); +const ChunkTemplate = require("./ChunkTemplate"); +const HotUpdateChunkTemplate = require("./HotUpdateChunkTemplate"); +const ModuleTemplate = require("./ModuleTemplate"); +const RuntimeTemplate = require("./RuntimeTemplate"); +const ChunkRenderError = require("./ChunkRenderError"); +const AsyncDependencyToInitialChunkError = require("./AsyncDependencyToInitialChunkError"); +const Stats = require("./Stats"); +const Semaphore = require("./util/Semaphore"); +const createHash = require("./util/createHash"); +const Queue = require("./util/Queue"); +const SortableSet = require("./util/SortableSet"); +const GraphHelpers = require("./GraphHelpers"); +const ModuleDependency = require("./dependencies/ModuleDependency"); +const compareLocations = require("./compareLocations"); + +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("./WebpackError")} WebpackError */ +/** @typedef {import("./DependenciesBlockVariable")} DependenciesBlockVariable */ +/** @typedef {import("./dependencies/SingleEntryDependency")} SingleEntryDependency */ +/** @typedef {import("./dependencies/MultiEntryDependency")} MultiEntryDependency */ +/** @typedef {import("./dependencies/DllEntryDependency")} DllEntryDependency */ +/** @typedef {import("./dependencies/DependencyReference")} DependencyReference */ +/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ +/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./Dependency").DependencyTemplate} DependencyTemplate */ +/** @typedef {import("./util/createHash").Hash} Hash */ + +// TODO use @callback +/** @typedef {{[assetName: string]: Source}} CompilationAssets */ +/** @typedef {(err: Error|null, result?: Module) => void } ModuleCallback */ +/** @typedef {(err?: Error|null, result?: Module) => void } ModuleChainCallback */ +/** @typedef {(module: Module) => void} OnModuleCallback */ +/** @typedef {(err?: Error|null) => void} Callback */ +/** @typedef {(d: Dependency) => any} DepBlockVarDependenciesCallback */ +/** @typedef {new (...args: any[]) => Dependency} DepConstructor */ +/** @typedef {{apply: () => void}} Plugin */ + +/** + * @typedef {Object} ModuleFactoryCreateDataContextInfo + * @property {string} issuer + * @property {string} compiler + */ + +/** + * @typedef {Object} ModuleFactoryCreateData + * @property {ModuleFactoryCreateDataContextInfo} contextInfo + * @property {any=} resolveOptions + * @property {string} context + * @property {Dependency[]} dependencies + */ + +/** + * @typedef {Object} ModuleFactory + * @property {(data: ModuleFactoryCreateData, callback: ModuleCallback) => any} create + */ + +/** + * @typedef {Object} SortedDependency + * @property {ModuleFactory} factory + * @property {Dependency[]} dependencies + */ + +/** + * @typedef {Object} AvailableModulesChunkGroupMapping + * @property {ChunkGroup} chunkGroup + * @property {Set<Module>} availableModules + */ + +/** + * @typedef {Object} DependenciesBlockLike + * @property {Dependency[]} dependencies + * @property {AsyncDependenciesBlock[]} blocks + * @property {DependenciesBlockVariable[]} variables + */ + +/** + * @param {Chunk} a first chunk to sort by id + * @param {Chunk} b second chunk to sort by id + * @returns {-1|0|1} sort value + */ +const byId = (a, b) => { + if (a.id !== null && b.id !== null) { + if (a.id < b.id) return -1; + if (a.id > b.id) return 1; + } + return 0; +}; + +/** + * @param {Module} a first module to sort by + * @param {Module} b second module to sort by + * @returns {-1|0|1} sort value + */ +const byIdOrIdentifier = (a, b) => { + if (a.id < b.id) return -1; + if (a.id > b.id) return 1; + const identA = a.identifier(); + const identB = b.identifier(); + if (identA < identB) return -1; + if (identA > identB) return 1; + return 0; +}; + +/** + * @param {Module} a first module to sort by + * @param {Module} b second module to sort by + * @returns {-1|0|1} sort value + */ +const byIndexOrIdentifier = (a, b) => { + if (a.index < b.index) return -1; + if (a.index > b.index) return 1; + const identA = a.identifier(); + const identB = b.identifier(); + if (identA < identB) return -1; + if (identA > identB) return 1; + return 0; +}; + +/** + * @param {Compilation} a first compilation to sort by + * @param {Compilation} b second compilation to sort by + * @returns {-1|0|1} sort value + */ +const byNameOrHash = (a, b) => { + if (a.name < b.name) return -1; + if (a.name > b.name) return 1; + if (a.fullHash < b.fullHash) return -1; + if (a.fullHash > b.fullHash) return 1; + return 0; +}; + +/** + * @param {DependenciesBlockVariable[]} variables DepBlock Variables to iterate over + * @param {DepBlockVarDependenciesCallback} fn callback to apply on iterated elements + * @returns {void} + */ +const iterationBlockVariable = (variables, fn) => { + for ( + let indexVariable = 0; + indexVariable < variables.length; + indexVariable++ + ) { + const varDep = variables[indexVariable].dependencies; + for (let indexVDep = 0; indexVDep < varDep.length; indexVDep++) { + fn(varDep[indexVDep]); + } + } +}; + +/** + * @template T + * @param {T[]} arr array of elements to iterate over + * @param {function(T): void} fn callback applied to each element + * @returns {void} + */ +const iterationOfArrayCallback = (arr, fn) => { + for (let index = 0; index < arr.length; index++) { + fn(arr[index]); + } +}; + +/** + * @template T + * @param {Set<T>} set set to add items to + * @param {Set<T>} otherSet set to add items from + * @returns {void} + */ +const addAllToSet = (set, otherSet) => { + for (const item of otherSet) { + set.add(item); + } +}; + +class Compilation extends Tapable { + /** + * Creates an instance of Compilation. + * @param {Compiler} compiler the compiler which created the compilation + */ + constructor(compiler) { + super(); + this.hooks = { + /** @type {SyncHook<Module>} */ + buildModule: new SyncHook(["module"]), + /** @type {SyncHook<Module>} */ + rebuildModule: new SyncHook(["module"]), + /** @type {SyncHook<Module, Error>} */ + failedModule: new SyncHook(["module", "error"]), + /** @type {SyncHook<Module>} */ + succeedModule: new SyncHook(["module"]), + + /** @type {SyncWaterfallHook<DependencyReference, Dependency, Module>} */ + dependencyReference: new SyncWaterfallHook([ + "dependencyReference", + "dependency", + "module" + ]), + + /** @type {SyncHook<Module[]>} */ + finishModules: new SyncHook(["modules"]), + /** @type {SyncHook<Module>} */ + finishRebuildingModule: new SyncHook(["module"]), + /** @type {SyncHook} */ + unseal: new SyncHook([]), + /** @type {SyncHook} */ + seal: new SyncHook([]), + + /** @type {SyncHook} */ + beforeChunks: new SyncHook([]), + /** @type {SyncHook<Chunk[]>} */ + afterChunks: new SyncHook(["chunks"]), + + /** @type {SyncBailHook<Module[]>} */ + optimizeDependenciesBasic: new SyncBailHook(["modules"]), + /** @type {SyncBailHook<Module[]>} */ + optimizeDependencies: new SyncBailHook(["modules"]), + /** @type {SyncBailHook<Module[]>} */ + optimizeDependenciesAdvanced: new SyncBailHook(["modules"]), + /** @type {SyncBailHook<Module[]>} */ + afterOptimizeDependencies: new SyncHook(["modules"]), + + /** @type {SyncHook} */ + optimize: new SyncHook([]), + /** @type {SyncBailHook<Module[]>} */ + optimizeModulesBasic: new SyncBailHook(["modules"]), + /** @type {SyncBailHook<Module[]>} */ + optimizeModules: new SyncBailHook(["modules"]), + /** @type {SyncBailHook<Module[]>} */ + optimizeModulesAdvanced: new SyncBailHook(["modules"]), + /** @type {SyncHook<Module[]>} */ + afterOptimizeModules: new SyncHook(["modules"]), + + /** @type {SyncBailHook<Chunk[], ChunkGroup[]>} */ + optimizeChunksBasic: new SyncBailHook(["chunks", "chunkGroups"]), + /** @type {SyncBailHook<Chunk[], ChunkGroup[]>} */ + optimizeChunks: new SyncBailHook(["chunks", "chunkGroups"]), + /** @type {SyncBailHook<Chunk[], ChunkGroup[]>} */ + optimizeChunksAdvanced: new SyncBailHook(["chunks", "chunkGroups"]), + /** @type {SyncHook<Chunk[], ChunkGroup[]>} */ + afterOptimizeChunks: new SyncHook(["chunks", "chunkGroups"]), + + /** @type {AsyncSeriesHook<Chunk[], Module[]>} */ + optimizeTree: new AsyncSeriesHook(["chunks", "modules"]), + /** @type {SyncHook<Chunk[], Module[]>} */ + afterOptimizeTree: new SyncHook(["chunks", "modules"]), + + /** @type {SyncBailHook<Chunk[], Module[]>} */ + optimizeChunkModulesBasic: new SyncBailHook(["chunks", "modules"]), + /** @type {SyncBailHook<Chunk[], Module[]>} */ + optimizeChunkModules: new SyncBailHook(["chunks", "modules"]), + /** @type {SyncBailHook<Chunk[], Module[]>} */ + optimizeChunkModulesAdvanced: new SyncBailHook(["chunks", "modules"]), + /** @type {SyncHook<Chunk[], Module[]>} */ + afterOptimizeChunkModules: new SyncHook(["chunks", "modules"]), + /** @type {SyncBailHook} */ + shouldRecord: new SyncBailHook([]), + + /** @type {SyncHook<Module[], any>} */ + reviveModules: new SyncHook(["modules", "records"]), + /** @type {SyncHook<Module[]>} */ + optimizeModuleOrder: new SyncHook(["modules"]), + /** @type {SyncHook<Module[]>} */ + advancedOptimizeModuleOrder: new SyncHook(["modules"]), + /** @type {SyncHook<Module[]>} */ + beforeModuleIds: new SyncHook(["modules"]), + /** @type {SyncHook<Module[]>} */ + moduleIds: new SyncHook(["modules"]), + /** @type {SyncHook<Module[]>} */ + optimizeModuleIds: new SyncHook(["modules"]), + /** @type {SyncHook<Module[]>} */ + afterOptimizeModuleIds: new SyncHook(["modules"]), + + /** @type {SyncHook<Chunk[], any>} */ + reviveChunks: new SyncHook(["chunks", "records"]), + /** @type {SyncHook<Chunk[]>} */ + optimizeChunkOrder: new SyncHook(["chunks"]), + /** @type {SyncHook<Chunk[]>} */ + beforeChunkIds: new SyncHook(["chunks"]), + /** @type {SyncHook<Chunk[]>} */ + optimizeChunkIds: new SyncHook(["chunks"]), + /** @type {SyncHook<Chunk[]>} */ + afterOptimizeChunkIds: new SyncHook(["chunks"]), + + /** @type {SyncHook<Module[], any>} */ + recordModules: new SyncHook(["modules", "records"]), + /** @type {SyncHook<Chunk[], any>} */ + recordChunks: new SyncHook(["chunks", "records"]), + + /** @type {SyncHook} */ + beforeHash: new SyncHook([]), + /** @type {SyncHook<Chunk>} */ + contentHash: new SyncHook(["chunk"]), + /** @type {SyncHook} */ + afterHash: new SyncHook([]), + /** @type {SyncHook<any>} */ + recordHash: new SyncHook(["records"]), + /** @type {SyncHook<Compilation, any>} */ + record: new SyncHook(["compilation", "records"]), + + /** @type {SyncHook} */ + beforeModuleAssets: new SyncHook([]), + /** @type {SyncBailHook} */ + shouldGenerateChunkAssets: new SyncBailHook([]), + /** @type {SyncHook} */ + beforeChunkAssets: new SyncHook([]), + /** @type {SyncHook<Chunk[]>} */ + additionalChunkAssets: new SyncHook(["chunks"]), + + /** @type {AsyncSeriesHook} */ + additionalAssets: new AsyncSeriesHook([]), + /** @type {AsyncSeriesHook<Chunk[]>} */ + optimizeChunkAssets: new AsyncSeriesHook(["chunks"]), + /** @type {SyncHook<Chunk[]>} */ + afterOptimizeChunkAssets: new SyncHook(["chunks"]), + /** @type {AsyncSeriesHook<CompilationAssets>} */ + optimizeAssets: new AsyncSeriesHook(["assets"]), + /** @type {SyncHook<CompilationAssets>} */ + afterOptimizeAssets: new SyncHook(["assets"]), + + /** @type {SyncBailHook} */ + needAdditionalSeal: new SyncBailHook([]), + /** @type {AsyncSeriesHook} */ + afterSeal: new AsyncSeriesHook([]), + + /** @type {SyncHook<Chunk, Hash>} */ + chunkHash: new SyncHook(["chunk", "chunkHash"]), + /** @type {SyncHook<Module, string>} */ + moduleAsset: new SyncHook(["module", "filename"]), + /** @type {SyncHook<Chunk, string>} */ + chunkAsset: new SyncHook(["chunk", "filename"]), + + /** @type {SyncWaterfallHook<string, TODO>} */ + assetPath: new SyncWaterfallHook(["filename", "data"]), // TODO MainTemplate + + /** @type {SyncBailHook} */ + needAdditionalPass: new SyncBailHook([]), + + /** @type {SyncHook<Compiler, string, number>} */ + childCompiler: new SyncHook([ + "childCompiler", + "compilerName", + "compilerIndex" + ]), + + // TODO the following hooks are weirdly located here + // TODO move them for webpack 5 + /** @type {SyncHook<object, Module>} */ + normalModuleLoader: new SyncHook(["loaderContext", "module"]), + + /** @type {SyncBailHook<Chunk[]>} */ + optimizeExtractedChunksBasic: new SyncBailHook(["chunks"]), + /** @type {SyncBailHook<Chunk[]>} */ + optimizeExtractedChunks: new SyncBailHook(["chunks"]), + /** @type {SyncBailHook<Chunk[]>} */ + optimizeExtractedChunksAdvanced: new SyncBailHook(["chunks"]), + /** @type {SyncHook<Chunk[]>} */ + afterOptimizeExtractedChunks: new SyncHook(["chunks"]) + }; + this._pluginCompat.tap("Compilation", options => { + switch (options.name) { + case "optimize-tree": + case "additional-assets": + case "optimize-chunk-assets": + case "optimize-assets": + case "after-seal": + options.async = true; + break; + } + }); + /** @type {string=} */ + this.name = undefined; + /** @type {Compiler} */ + this.compiler = compiler; + this.resolverFactory = compiler.resolverFactory; + this.inputFileSystem = compiler.inputFileSystem; + this.requestShortener = compiler.requestShortener; + + const options = (this.options = compiler.options); + this.outputOptions = options && options.output; + /** @type {boolean=} */ + this.bail = options && options.bail; + this.profile = options && options.profile; + this.performance = options && options.performance; + + this.mainTemplate = new MainTemplate(this.outputOptions); + this.chunkTemplate = new ChunkTemplate(this.outputOptions); + this.hotUpdateChunkTemplate = new HotUpdateChunkTemplate( + this.outputOptions + ); + this.runtimeTemplate = new RuntimeTemplate( + this.outputOptions, + this.requestShortener + ); + this.moduleTemplates = { + javascript: new ModuleTemplate(this.runtimeTemplate, "javascript"), + webassembly: new ModuleTemplate(this.runtimeTemplate, "webassembly") + }; + + this.semaphore = new Semaphore(options.parallelism || 100); + + this.entries = []; + /** @private @type {{name: string, request: string, module: Module}[]} */ + this._preparedEntrypoints = []; + this.entrypoints = new Map(); + /** @type {Chunk[]} */ + this.chunks = []; + /** @type {ChunkGroup[]} */ + this.chunkGroups = []; + /** @type {Map<string, ChunkGroup>} */ + this.namedChunkGroups = new Map(); + /** @type {Map<string, Chunk>} */ + this.namedChunks = new Map(); + /** @type {Module[]} */ + this.modules = []; + /** @private @type {Map<string, Module>} */ + this._modules = new Map(); + this.cache = null; + this.records = null; + /** @type {string[]} */ + this.additionalChunkAssets = []; + /** @type {CompilationAssets} */ + this.assets = {}; + /** @type {WebpackError[]} */ + this.errors = []; + /** @type {WebpackError[]} */ + this.warnings = []; + /** @type {Compilation[]} */ + this.children = []; + /** @type {Map<DepConstructor, ModuleFactory>} */ + this.dependencyFactories = new Map(); + /** @type {Map<DepConstructor, DependencyTemplate>} */ + this.dependencyTemplates = new Map(); + // TODO refactor this in webpack 5 to a custom DependencyTemplates class with a hash property + // @ts-ignore + this.dependencyTemplates.set("hash", ""); + this.childrenCounters = {}; + /** @type {Set<number|string>} */ + this.usedChunkIds = null; + /** @type {Set<number>} */ + this.usedModuleIds = null; + /** @type {Map<string, number>=} */ + this.fileTimestamps = undefined; + /** @type {Map<string, number>=} */ + this.contextTimestamps = undefined; + /** @type {Set<string>=} */ + this.compilationDependencies = undefined; + /** @private @type {Map<Module, Callback[]>} */ + this._buildingModules = new Map(); + /** @private @type {Map<Module, Callback[]>} */ + this._rebuildingModules = new Map(); + } + + getStats() { + return new Stats(this); + } + + /** + * @typedef {Object} AddModuleResult + * @property {Module} module the added or existing module + * @property {boolean} issuer was this the first request for this module + * @property {boolean} build should the module be build + * @property {boolean} dependencies should dependencies be walked + */ + + /** + * @param {Module} module module to be added that was created + * @param {any=} cacheGroup cacheGroup it is apart of + * @returns {AddModuleResult} returns meta about whether or not the module had built + * had an issuer, or any dependnecies + */ + addModule(module, cacheGroup) { + const identifier = module.identifier(); + const alreadyAddedModule = this._modules.get(identifier); + if (alreadyAddedModule) { + return { + module: alreadyAddedModule, + issuer: false, + build: false, + dependencies: false + }; + } + const cacheName = (cacheGroup || "m") + identifier; + if (this.cache && this.cache[cacheName]) { + const cacheModule = this.cache[cacheName]; + + if (typeof cacheModule.updateCacheModule === "function") { + cacheModule.updateCacheModule(module); + } + + let rebuild = true; + if (this.fileTimestamps && this.contextTimestamps) { + rebuild = cacheModule.needRebuild( + this.fileTimestamps, + this.contextTimestamps + ); + } + + if (!rebuild) { + cacheModule.disconnect(); + this._modules.set(identifier, cacheModule); + this.modules.push(cacheModule); + for (const err of cacheModule.errors) { + this.errors.push(err); + } + for (const err of cacheModule.warnings) { + this.warnings.push(err); + } + return { + module: cacheModule, + issuer: true, + build: false, + dependencies: true + }; + } + cacheModule.unbuild(); + module = cacheModule; + } + this._modules.set(identifier, module); + if (this.cache) { + this.cache[cacheName] = module; + } + this.modules.push(module); + return { + module: module, + issuer: true, + build: true, + dependencies: true + }; + } + + /** + * Fetches a module from a compilation by its identifier + * @param {Module} module the module provided + * @returns {Module} the module requested + */ + getModule(module) { + const identifier = module.identifier(); + return this._modules.get(identifier); + } + + /** + * Attempts to search for a module by its identifier + * @param {string} identifier identifier (usually path) for module + * @returns {Module|undefined} attempt to search for module and return it, else undefined + */ + findModule(identifier) { + return this._modules.get(identifier); + } + + /** + * @param {Module} module module with its callback list + * @param {Callback} callback the callback function + * @returns {void} + */ + waitForBuildingFinished(module, callback) { + let callbackList = this._buildingModules.get(module); + if (callbackList) { + callbackList.push(() => callback()); + } else { + process.nextTick(callback); + } + } + + /** + * Builds the module object + * + * @param {Module} module module to be built + * @param {boolean} optional optional flag + * @param {Module=} origin origin module this module build was requested from + * @param {Dependency[]=} dependencies optional dependencies from the module to be built + * @param {TODO} thisCallback the callback + * @returns {TODO} returns the callback function with results + */ + buildModule(module, optional, origin, dependencies, thisCallback) { + let callbackList = this._buildingModules.get(module); + if (callbackList) { + callbackList.push(thisCallback); + return; + } + this._buildingModules.set(module, (callbackList = [thisCallback])); + + const callback = err => { + this._buildingModules.delete(module); + for (const cb of callbackList) { + cb(err); + } + }; + + this.hooks.buildModule.call(module); + module.build( + this.options, + this, + this.resolverFactory.get("normal", module.resolveOptions), + this.inputFileSystem, + error => { + const errors = module.errors; + for (let indexError = 0; indexError < errors.length; indexError++) { + const err = errors[indexError]; + err.origin = origin; + err.dependencies = dependencies; + if (optional) { + this.warnings.push(err); + } else { + this.errors.push(err); + } + } + + const warnings = module.warnings; + for ( + let indexWarning = 0; + indexWarning < warnings.length; + indexWarning++ + ) { + const war = warnings[indexWarning]; + war.origin = origin; + war.dependencies = dependencies; + this.warnings.push(war); + } + module.dependencies.sort((a, b) => compareLocations(a.loc, b.loc)); + if (error) { + this.hooks.failedModule.call(module, error); + return callback(error); + } + this.hooks.succeedModule.call(module); + return callback(); + } + ); + } + + /** + * @param {Module} module to be processed for deps + * @param {ModuleCallback} callback callback to be triggered + * @returns {void} + */ + processModuleDependencies(module, callback) { + const dependencies = new Map(); + + const addDependency = dep => { + const resourceIdent = dep.getResourceIdentifier(); + if (resourceIdent) { + const factory = this.dependencyFactories.get(dep.constructor); + if (factory === undefined) { + throw new Error( + `No module factory available for dependency type: ${ + dep.constructor.name + }` + ); + } + let innerMap = dependencies.get(factory); + if (innerMap === undefined) { + dependencies.set(factory, (innerMap = new Map())); + } + let list = innerMap.get(resourceIdent); + if (list === undefined) innerMap.set(resourceIdent, (list = [])); + list.push(dep); + } + }; + + const addDependenciesBlock = block => { + if (block.dependencies) { + iterationOfArrayCallback(block.dependencies, addDependency); + } + if (block.blocks) { + iterationOfArrayCallback(block.blocks, addDependenciesBlock); + } + if (block.variables) { + iterationBlockVariable(block.variables, addDependency); + } + }; + + try { + addDependenciesBlock(module); + } catch (e) { + callback(e); + } + + const sortedDependencies = []; + + for (const pair1 of dependencies) { + for (const pair2 of pair1[1]) { + sortedDependencies.push({ + factory: pair1[0], + dependencies: pair2[1] + }); + } + } + + this.addModuleDependencies( + module, + sortedDependencies, + this.bail, + null, + true, + callback + ); + } + + /** + * @param {Module} module module to add deps to + * @param {SortedDependency[]} dependencies set of sorted dependencies to iterate through + * @param {(boolean|null)=} bail whether to bail or not + * @param {TODO} cacheGroup optional cacheGroup + * @param {boolean} recursive whether it is recursive traversal + * @param {function} callback callback for when dependencies are finished being added + * @returns {void} + */ + addModuleDependencies( + module, + dependencies, + bail, + cacheGroup, + recursive, + callback + ) { + const start = this.profile && Date.now(); + const currentProfile = this.profile && {}; + + asyncLib.forEach( + dependencies, + (item, callback) => { + const dependencies = item.dependencies; + + const errorAndCallback = err => { + err.origin = module; + err.dependencies = dependencies; + this.errors.push(err); + if (bail) { + callback(err); + } else { + callback(); + } + }; + const warningAndCallback = err => { + err.origin = module; + this.warnings.push(err); + callback(); + }; + + const semaphore = this.semaphore; + semaphore.acquire(() => { + const factory = item.factory; + factory.create( + { + contextInfo: { + issuer: module.nameForCondition && module.nameForCondition(), + compiler: this.compiler.name + }, + resolveOptions: module.resolveOptions, + context: module.context, + dependencies: dependencies + }, + (err, dependentModule) => { + let afterFactory; + + const isOptional = () => { + return dependencies.every(d => d.optional); + }; + + const errorOrWarningAndCallback = err => { + if (isOptional()) { + return warningAndCallback(err); + } else { + return errorAndCallback(err); + } + }; + + if (err) { + semaphore.release(); + return errorOrWarningAndCallback( + new ModuleNotFoundError(module, err) + ); + } + if (!dependentModule) { + semaphore.release(); + return process.nextTick(callback); + } + if (currentProfile) { + afterFactory = Date.now(); + currentProfile.factory = afterFactory - start; + } + + const iterationDependencies = depend => { + for (let index = 0; index < depend.length; index++) { + const dep = depend[index]; + dep.module = dependentModule; + dependentModule.addReason(module, dep); + } + }; + + const addModuleResult = this.addModule( + dependentModule, + cacheGroup + ); + dependentModule = addModuleResult.module; + iterationDependencies(dependencies); + + const afterBuild = () => { + if (currentProfile) { + const afterBuilding = Date.now(); + currentProfile.building = afterBuilding - afterFactory; + } + + if (recursive && addModuleResult.dependencies) { + this.processModuleDependencies(dependentModule, callback); + } else { + return callback(); + } + }; + + if (addModuleResult.issuer) { + if (currentProfile) { + dependentModule.profile = currentProfile; + } + + dependentModule.issuer = module; + } else { + if (this.profile) { + if (module.profile) { + const time = Date.now() - start; + if ( + !module.profile.dependencies || + time > module.profile.dependencies + ) { + module.profile.dependencies = time; + } + } + } + } + + if (addModuleResult.build) { + this.buildModule( + dependentModule, + isOptional(), + module, + dependencies, + err => { + if (err) { + semaphore.release(); + return errorOrWarningAndCallback(err); + } + + if (currentProfile) { + const afterBuilding = Date.now(); + currentProfile.building = afterBuilding - afterFactory; + } + + semaphore.release(); + afterBuild(); + } + ); + } else { + semaphore.release(); + this.waitForBuildingFinished(dependentModule, afterBuild); + } + } + ); + }); + }, + err => { + // In V8, the Error objects keep a reference to the functions on the stack. These warnings & + // errors are created inside closures that keep a reference to the Compilation, so errors are + // leaking the Compilation object. + + if (err) { + // eslint-disable-next-line no-self-assign + err.stack = err.stack; + return callback(err); + } + + return process.nextTick(callback); + } + ); + } + + /** + * + * @param {string} context context string path + * @param {Dependency} dependency dependency used to create Module chain + * @param {OnModuleCallback} onModule function invoked on modules creation + * @param {ModuleChainCallback} callback callback for when module chain is complete + * @returns {void} will throw if dependency instance is not a valid Dependency + */ + _addModuleChain(context, dependency, onModule, callback) { + const start = this.profile && Date.now(); + const currentProfile = this.profile && {}; + + const errorAndCallback = this.bail + ? err => { + callback(err); + } + : err => { + err.dependencies = [dependency]; + this.errors.push(err); + callback(); + }; + + if ( + typeof dependency !== "object" || + dependency === null || + !dependency.constructor + ) { + throw new Error("Parameter 'dependency' must be a Dependency"); + } + const Dep = /** @type {DepConstructor} */ (dependency.constructor); + const moduleFactory = this.dependencyFactories.get(Dep); + if (!moduleFactory) { + throw new Error( + `No dependency factory available for this dependency type: ${ + dependency.constructor.name + }` + ); + } + + this.semaphore.acquire(() => { + moduleFactory.create( + { + contextInfo: { + issuer: "", + compiler: this.compiler.name + }, + context: context, + dependencies: [dependency] + }, + (err, module) => { + if (err) { + this.semaphore.release(); + return errorAndCallback(new EntryModuleNotFoundError(err)); + } + + let afterFactory; + + if (currentProfile) { + afterFactory = Date.now(); + currentProfile.factory = afterFactory - start; + } + + const addModuleResult = this.addModule(module); + module = addModuleResult.module; + + onModule(module); + + dependency.module = module; + module.addReason(null, dependency); + + const afterBuild = () => { + if (currentProfile) { + const afterBuilding = Date.now(); + currentProfile.building = afterBuilding - afterFactory; + } + + if (addModuleResult.dependencies) { + this.processModuleDependencies(module, err => { + if (err) return callback(err); + callback(null, module); + }); + } else { + return callback(null, module); + } + }; + + if (addModuleResult.issuer) { + if (currentProfile) { + module.profile = currentProfile; + } + } + + if (addModuleResult.build) { + this.buildModule(module, false, null, null, err => { + if (err) { + this.semaphore.release(); + return errorAndCallback(err); + } + + if (currentProfile) { + const afterBuilding = Date.now(); + currentProfile.building = afterBuilding - afterFactory; + } + + this.semaphore.release(); + afterBuild(); + }); + } else { + this.semaphore.release(); + this.waitForBuildingFinished(module, afterBuild); + } + } + ); + }); + } + + /** + * + * @param {string} context context path for entry + * @param {Dependency} entry entry dependency being created + * @param {string} name name of entry + * @param {ModuleCallback} callback callback function + * @returns {void} returns + */ + addEntry(context, entry, name, callback) { + const slot = { + name: name, + // TODO webpack 5 remove `request` + request: null, + module: null + }; + + if (entry instanceof ModuleDependency) { + slot.request = entry.request; + } + + // TODO webpack 5: merge modules instead when multiple entry modules are supported + const idx = this._preparedEntrypoints.findIndex(slot => slot.name === name); + if (idx >= 0) { + // Overwrite existing entrypoint + this._preparedEntrypoints[idx] = slot; + } else { + this._preparedEntrypoints.push(slot); + } + this._addModuleChain( + context, + entry, + module => { + this.entries.push(module); + }, + (err, module) => { + if (err) { + return callback(err); + } + + if (module) { + slot.module = module; + } else { + const idx = this._preparedEntrypoints.indexOf(slot); + if (idx >= 0) { + this._preparedEntrypoints.splice(idx, 1); + } + } + return callback(null, module); + } + ); + } + + /** + * @param {string} context context path string + * @param {Dependency} dependency dep used to create module + * @param {ModuleCallback} callback module callback sending module up a level + * @returns {void} + */ + prefetch(context, dependency, callback) { + this._addModuleChain( + context, + dependency, + module => { + module.prefetched = true; + }, + callback + ); + } + + /** + * @param {Module} module module to be rebuilt + * @param {Callback} thisCallback callback when module finishes rebuilding + * @returns {void} + */ + rebuildModule(module, thisCallback) { + let callbackList = this._rebuildingModules.get(module); + if (callbackList) { + callbackList.push(thisCallback); + return; + } + this._rebuildingModules.set(module, (callbackList = [thisCallback])); + + const callback = err => { + this._rebuildingModules.delete(module); + for (const cb of callbackList) { + cb(err); + } + }; + + this.hooks.rebuildModule.call(module); + const oldDependencies = module.dependencies.slice(); + const oldVariables = module.variables.slice(); + const oldBlocks = module.blocks.slice(); + module.unbuild(); + this.buildModule(module, false, module, null, err => { + if (err) { + this.hooks.finishRebuildingModule.call(module); + return callback(err); + } + + this.processModuleDependencies(module, err => { + if (err) return callback(err); + this.removeReasonsOfDependencyBlock(module, { + dependencies: oldDependencies, + variables: oldVariables, + blocks: oldBlocks + }); + this.hooks.finishRebuildingModule.call(module); + callback(); + }); + }); + } + + finish() { + const modules = this.modules; + this.hooks.finishModules.call(modules); + + for (let index = 0; index < modules.length; index++) { + const module = modules[index]; + this.reportDependencyErrorsAndWarnings(module, [module]); + } + } + + unseal() { + this.hooks.unseal.call(); + this.chunks.length = 0; + this.chunkGroups.length = 0; + this.namedChunks.clear(); + this.namedChunkGroups.clear(); + this.additionalChunkAssets.length = 0; + this.assets = {}; + for (const module of this.modules) { + module.unseal(); + } + } + + /** + * @param {Callback} callback signals when the seal method is finishes + * @returns {void} + */ + seal(callback) { + this.hooks.seal.call(); + + while ( + this.hooks.optimizeDependenciesBasic.call(this.modules) || + this.hooks.optimizeDependencies.call(this.modules) || + this.hooks.optimizeDependenciesAdvanced.call(this.modules) + ) { + /* empty */ + } + this.hooks.afterOptimizeDependencies.call(this.modules); + + this.hooks.beforeChunks.call(); + for (const preparedEntrypoint of this._preparedEntrypoints) { + const module = preparedEntrypoint.module; + const name = preparedEntrypoint.name; + const chunk = this.addChunk(name); + const entrypoint = new Entrypoint(name); + entrypoint.setRuntimeChunk(chunk); + entrypoint.addOrigin(null, name, preparedEntrypoint.request); + this.namedChunkGroups.set(name, entrypoint); + this.entrypoints.set(name, entrypoint); + this.chunkGroups.push(entrypoint); + + GraphHelpers.connectChunkGroupAndChunk(entrypoint, chunk); + GraphHelpers.connectChunkAndModule(chunk, module); + + chunk.entryModule = module; + chunk.name = name; + + this.assignDepth(module); + } + this.processDependenciesBlocksForChunkGroups(this.chunkGroups.slice()); + this.sortModules(this.modules); + this.hooks.afterChunks.call(this.chunks); + + this.hooks.optimize.call(); + + while ( + this.hooks.optimizeModulesBasic.call(this.modules) || + this.hooks.optimizeModules.call(this.modules) || + this.hooks.optimizeModulesAdvanced.call(this.modules) + ) { + /* empty */ + } + this.hooks.afterOptimizeModules.call(this.modules); + + while ( + this.hooks.optimizeChunksBasic.call(this.chunks, this.chunkGroups) || + this.hooks.optimizeChunks.call(this.chunks, this.chunkGroups) || + this.hooks.optimizeChunksAdvanced.call(this.chunks, this.chunkGroups) + ) { + /* empty */ + } + this.hooks.afterOptimizeChunks.call(this.chunks, this.chunkGroups); + + this.hooks.optimizeTree.callAsync(this.chunks, this.modules, err => { + if (err) { + return callback(err); + } + + this.hooks.afterOptimizeTree.call(this.chunks, this.modules); + + while ( + this.hooks.optimizeChunkModulesBasic.call(this.chunks, this.modules) || + this.hooks.optimizeChunkModules.call(this.chunks, this.modules) || + this.hooks.optimizeChunkModulesAdvanced.call(this.chunks, this.modules) + ) { + /* empty */ + } + this.hooks.afterOptimizeChunkModules.call(this.chunks, this.modules); + + const shouldRecord = this.hooks.shouldRecord.call() !== false; + + this.hooks.reviveModules.call(this.modules, this.records); + this.hooks.optimizeModuleOrder.call(this.modules); + this.hooks.advancedOptimizeModuleOrder.call(this.modules); + this.hooks.beforeModuleIds.call(this.modules); + this.hooks.moduleIds.call(this.modules); + this.applyModuleIds(); + this.hooks.optimizeModuleIds.call(this.modules); + this.hooks.afterOptimizeModuleIds.call(this.modules); + + this.sortItemsWithModuleIds(); + + this.hooks.reviveChunks.call(this.chunks, this.records); + this.hooks.optimizeChunkOrder.call(this.chunks); + this.hooks.beforeChunkIds.call(this.chunks); + this.applyChunkIds(); + this.hooks.optimizeChunkIds.call(this.chunks); + this.hooks.afterOptimizeChunkIds.call(this.chunks); + + this.sortItemsWithChunkIds(); + + if (shouldRecord) { + this.hooks.recordModules.call(this.modules, this.records); + this.hooks.recordChunks.call(this.chunks, this.records); + } + + this.hooks.beforeHash.call(); + this.createHash(); + this.hooks.afterHash.call(); + + if (shouldRecord) { + this.hooks.recordHash.call(this.records); + } + + this.hooks.beforeModuleAssets.call(); + this.createModuleAssets(); + if (this.hooks.shouldGenerateChunkAssets.call() !== false) { + this.hooks.beforeChunkAssets.call(); + this.createChunkAssets(); + } + this.hooks.additionalChunkAssets.call(this.chunks); + this.summarizeDependencies(); + if (shouldRecord) { + this.hooks.record.call(this, this.records); + } + + this.hooks.additionalAssets.callAsync(err => { + if (err) { + return callback(err); + } + this.hooks.optimizeChunkAssets.callAsync(this.chunks, err => { + if (err) { + return callback(err); + } + this.hooks.afterOptimizeChunkAssets.call(this.chunks); + this.hooks.optimizeAssets.callAsync(this.assets, err => { + if (err) { + return callback(err); + } + this.hooks.afterOptimizeAssets.call(this.assets); + if (this.hooks.needAdditionalSeal.call()) { + this.unseal(); + return this.seal(callback); + } + return this.hooks.afterSeal.callAsync(callback); + }); + }); + }); + }); + } + + /** + * @param {Module[]} modules the modules array on compilation to perform the sort for + * @returns {void} + */ + sortModules(modules) { + // TODO webpack 5: this should only be enabled when `moduleIds: "natural"` + // TODO move it into a plugin (NaturalModuleIdsPlugin) and use this in WebpackOptionsApply + // TODO remove this method + modules.sort(byIndexOrIdentifier); + } + + /** + * @param {Module} module moulde to report from + * @param {DependenciesBlock[]} blocks blocks to report from + * @returns {void} + */ + reportDependencyErrorsAndWarnings(module, blocks) { + for (let indexBlock = 0; indexBlock < blocks.length; indexBlock++) { + const block = blocks[indexBlock]; + const dependencies = block.dependencies; + + for (let indexDep = 0; indexDep < dependencies.length; indexDep++) { + const d = dependencies[indexDep]; + + const warnings = d.getWarnings(); + if (warnings) { + for (let indexWar = 0; indexWar < warnings.length; indexWar++) { + const w = warnings[indexWar]; + + const warning = new ModuleDependencyWarning(module, w, d.loc); + this.warnings.push(warning); + } + } + const errors = d.getErrors(); + if (errors) { + for (let indexErr = 0; indexErr < errors.length; indexErr++) { + const e = errors[indexErr]; + + const error = new ModuleDependencyError(module, e, d.loc); + this.errors.push(error); + } + } + } + + this.reportDependencyErrorsAndWarnings(module, block.blocks); + } + } + + /** + * @param {TODO} groupOptions options for the chunk group + * @param {Module} module the module the references the chunk group + * @param {DependencyLocation} loc the location from with the chunk group is referenced (inside of module) + * @param {string} request the request from which the the chunk group is referenced + * @returns {ChunkGroup} the new or existing chunk group + */ + addChunkInGroup(groupOptions, module, loc, request) { + if (typeof groupOptions === "string") { + groupOptions = { name: groupOptions }; + } + const name = groupOptions.name; + if (name) { + const chunkGroup = this.namedChunkGroups.get(name); + if (chunkGroup !== undefined) { + chunkGroup.addOptions(groupOptions); + if (module) { + chunkGroup.addOrigin(module, loc, request); + } + return chunkGroup; + } + } + const chunkGroup = new ChunkGroup(groupOptions); + if (module) chunkGroup.addOrigin(module, loc, request); + const chunk = this.addChunk(name); + + GraphHelpers.connectChunkGroupAndChunk(chunkGroup, chunk); + + this.chunkGroups.push(chunkGroup); + if (name) { + this.namedChunkGroups.set(name, chunkGroup); + } + return chunkGroup; + } + + /** + * This method first looks to see if a name is provided for a new chunk, + * and first looks to see if any named chunks already exist and reuse that chunk instead. + * + * @param {string=} name optional chunk name to be provided + * @returns {Chunk} create a chunk (invoked during seal event) + */ + addChunk(name) { + if (name) { + const chunk = this.namedChunks.get(name); + if (chunk !== undefined) { + return chunk; + } + } + const chunk = new Chunk(name); + this.chunks.push(chunk); + if (name) { + this.namedChunks.set(name, chunk); + } + return chunk; + } + + /** + * @param {Module} module module to assign depth + * @returns {void} + */ + assignDepth(module) { + const queue = new Set([module]); + let depth; + + module.depth = 0; + + /** + * @param {Module} module module for processeing + * @returns {void} + */ + const enqueueJob = module => { + const d = module.depth; + if (typeof d === "number" && d <= depth) return; + queue.add(module); + module.depth = depth; + }; + + /** + * @param {Dependency} dependency dependency to assign depth to + * @returns {void} + */ + const assignDepthToDependency = dependency => { + if (dependency.module) { + enqueueJob(dependency.module); + } + }; + + /** + * @param {DependenciesBlock} block block to assign depth to + * @returns {void} + */ + const assignDepthToDependencyBlock = block => { + if (block.variables) { + iterationBlockVariable(block.variables, assignDepthToDependency); + } + + if (block.dependencies) { + iterationOfArrayCallback(block.dependencies, assignDepthToDependency); + } + + if (block.blocks) { + iterationOfArrayCallback(block.blocks, assignDepthToDependencyBlock); + } + }; + + for (module of queue) { + queue.delete(module); + depth = module.depth; + + depth++; + assignDepthToDependencyBlock(module); + } + } + + /** + * @param {Module} module the module containing the dependency + * @param {Dependency} dependency the dependency + * @returns {DependencyReference} a reference for the dependency + */ + getDependencyReference(module, dependency) { + // TODO remove dep.getReference existence check in webpack 5 + if (typeof dependency.getReference !== "function") return null; + const ref = dependency.getReference(); + if (!ref) return null; + return this.hooks.dependencyReference.call(ref, dependency, module); + } + + /** + * This method creates the Chunk graph from the Module graph + * @private + * @param {TODO[]} inputChunkGroups chunk groups which are processed + * @returns {void} + */ + processDependenciesBlocksForChunkGroups(inputChunkGroups) { + // Process is splitting into two parts: + // Part one traverse the module graph and builds a very basic chunks graph + // in chunkDependencies. + // Part two traverse every possible way through the basic chunk graph and + // tracks the available modules. While traversing it connects chunks with + // eachother and Blocks with Chunks. It stops traversing when all modules + // for a chunk are already available. So it doesn't connect unneeded chunks. + + /** @type {Map<ChunkGroup, {block: AsyncDependenciesBlock, chunkGroup: ChunkGroup}[]>} */ + const chunkDependencies = new Map(); + const allCreatedChunkGroups = new Set(); + + // PREPARE + /** @type {Map<DependenciesBlock, { modules: Module[], blocks: AsyncDependenciesBlock[]}>} */ + const blockInfoMap = new Map(); + + /** + * @param {Dependency} d dependency to iterate over + * @returns {void} + */ + const iteratorDependency = d => { + // We skip Dependencies without Reference + const ref = this.getDependencyReference(currentModule, d); + if (!ref) { + return; + } + // We skip Dependencies without Module pointer + const refModule = ref.module; + if (!refModule) { + return; + } + // We skip weak Dependencies + if (ref.weak) { + return; + } + + blockInfoModules.add(refModule); + }; + + /** + * @param {AsyncDependenciesBlock} b blocks to prepare + * @returns {void} + */ + const iteratorBlockPrepare = b => { + blockInfoBlocks.push(b); + blockQueue.push(b); + }; + + /** @type {Module} */ + let currentModule; + /** @type {DependenciesBlock} */ + let block; + /** @type {DependenciesBlock[]} */ + let blockQueue; + /** @type {Set<Module>} */ + let blockInfoModules; + /** @type {AsyncDependenciesBlock[]} */ + let blockInfoBlocks; + + for (const module of this.modules) { + blockQueue = [module]; + currentModule = module; + while (blockQueue.length > 0) { + block = blockQueue.pop(); + blockInfoModules = new Set(); + blockInfoBlocks = []; + + if (block.variables) { + iterationBlockVariable(block.variables, iteratorDependency); + } + + if (block.dependencies) { + iterationOfArrayCallback(block.dependencies, iteratorDependency); + } + + if (block.blocks) { + iterationOfArrayCallback(block.blocks, iteratorBlockPrepare); + } + + const blockInfo = { + modules: Array.from(blockInfoModules), + blocks: blockInfoBlocks + }; + blockInfoMap.set(block, blockInfo); + } + } + + // PART ONE + + /** @type {Map<ChunkGroup, { index: number, index2: number }>} */ + const chunkGroupCounters = new Map(); + for (const chunkGroup of inputChunkGroups) { + chunkGroupCounters.set(chunkGroup, { index: 0, index2: 0 }); + } + + let nextFreeModuleIndex = 0; + let nextFreeModuleIndex2 = 0; + + /** @type {Map<DependenciesBlock, ChunkGroup>} */ + const blockChunkGroups = new Map(); + + /** @type {Set<DependenciesBlock>} */ + const blocksWithNestedBlocks = new Set(); + + const ADD_AND_ENTER_MODULE = 0; + const ENTER_MODULE = 1; + const PROCESS_BLOCK = 2; + const LEAVE_MODULE = 3; + + /** + * @typedef {Object} QueueItem + * @property {number} action + * @property {DependenciesBlock} block + * @property {Module} module + * @property {Chunk} chunk + * @property {ChunkGroup} chunkGroup + */ + + /** + * @param {ChunkGroup} chunkGroup chunk group + * @returns {QueueItem} queue item + */ + const chunkGroupToQueueItem = chunkGroup => ({ + action: ENTER_MODULE, + block: chunkGroup.chunks[0].entryModule, + module: chunkGroup.chunks[0].entryModule, + chunk: chunkGroup.chunks[0], + chunkGroup + }); + + // Start with the provided modules/chunks + /** @type {QueueItem[]} */ + let queue = inputChunkGroups.map(chunkGroupToQueueItem).reverse(); + /** @type {QueueItem[]} */ + let queueDelayed = []; + + /** @type {Module} */ + let module; + /** @type {Chunk} */ + let chunk; + /** @type {ChunkGroup} */ + let chunkGroup; + + // For each async Block in graph + /** + * @param {AsyncDependenciesBlock} b iterating over each Async DepBlock + * @returns {void} + */ + const iteratorBlock = b => { + // 1. We create a chunk for this Block + // but only once (blockChunkGroups map) + let c = blockChunkGroups.get(b); + if (c === undefined) { + c = this.namedChunkGroups.get(b.chunkName); + if (c && c.isInitial()) { + this.errors.push( + new AsyncDependencyToInitialChunkError(b.chunkName, module, b.loc) + ); + c = chunkGroup; + } else { + c = this.addChunkInGroup( + b.groupOptions || b.chunkName, + module, + b.loc, + b.request + ); + chunkGroupCounters.set(c, { index: 0, index2: 0 }); + blockChunkGroups.set(b, c); + allCreatedChunkGroups.add(c); + } + } else { + // TODO webpack 5 remove addOptions check + if (c.addOptions) c.addOptions(b.groupOptions); + c.addOrigin(module, b.loc, b.request); + } + + // 2. We store the Block+Chunk mapping as dependency for the chunk + let deps = chunkDependencies.get(chunkGroup); + if (!deps) chunkDependencies.set(chunkGroup, (deps = [])); + deps.push({ + block: b, + chunkGroup: c + }); + + // 3. We enqueue the DependenciesBlock for traversal + queueDelayed.push({ + action: PROCESS_BLOCK, + block: b, + module: module, + chunk: c.chunks[0], + chunkGroup: c + }); + }; + + // Iterative traversal of the Module graph + // Recursive would be simpler to write but could result in Stack Overflows + while (queue.length) { + while (queue.length) { + const queueItem = queue.pop(); + module = queueItem.module; + block = queueItem.block; + chunk = queueItem.chunk; + chunkGroup = queueItem.chunkGroup; + + switch (queueItem.action) { + case ADD_AND_ENTER_MODULE: { + // We connect Module and Chunk when not already done + if (chunk.addModule(module)) { + module.addChunk(chunk); + } else { + // already connected, skip it + break; + } + } + // fallthrough + case ENTER_MODULE: { + if (chunkGroup !== undefined) { + const index = chunkGroup.getModuleIndex(module); + if (index === undefined) { + chunkGroup.setModuleIndex( + module, + chunkGroupCounters.get(chunkGroup).index++ + ); + } + } + + if (module.index === null) { + module.index = nextFreeModuleIndex++; + } + + queue.push({ + action: LEAVE_MODULE, + block, + module, + chunk, + chunkGroup + }); + } + // fallthrough + case PROCESS_BLOCK: { + // get prepared block info + const blockInfo = blockInfoMap.get(block); + + // Traverse all referenced modules + for (let i = blockInfo.modules.length - 1; i >= 0; i--) { + const refModule = blockInfo.modules[i]; + if (chunk.containsModule(refModule)) { + // skip early if already connected + continue; + } + // enqueue the add and enter to enter in the correct order + // this is relevant with circular dependencies + queue.push({ + action: ADD_AND_ENTER_MODULE, + block: refModule, + module: refModule, + chunk, + chunkGroup + }); + } + + // Traverse all Blocks + iterationOfArrayCallback(blockInfo.blocks, iteratorBlock); + + if (blockInfo.blocks.length > 0 && module !== block) { + blocksWithNestedBlocks.add(block); + } + break; + } + case LEAVE_MODULE: { + if (chunkGroup !== undefined) { + const index = chunkGroup.getModuleIndex2(module); + if (index === undefined) { + chunkGroup.setModuleIndex2( + module, + chunkGroupCounters.get(chunkGroup).index2++ + ); + } + } + + if (module.index2 === null) { + module.index2 = nextFreeModuleIndex2++; + } + break; + } + } + } + const tempQueue = queue; + queue = queueDelayed.reverse(); + queueDelayed = tempQueue; + } + + // PART TWO + /** @type {Set<Module>} */ + let availableModules; + let newAvailableModules; + /** @type {Queue<AvailableModulesChunkGroupMapping>} */ + const queue2 = new Queue( + inputChunkGroups.map(chunkGroup => ({ + chunkGroup, + availableModules: new Set() + })) + ); + + /** + * Helper function to check if all modules of a chunk are available + * + * @param {ChunkGroup} chunkGroup the chunkGroup to scan + * @param {Set<Module>} availableModules the comparitor set + * @returns {boolean} return true if all modules of a chunk are available + */ + const areModulesAvailable = (chunkGroup, availableModules) => { + for (const chunk of chunkGroup.chunks) { + for (const module of chunk.modulesIterable) { + if (!availableModules.has(module)) return false; + } + } + return true; + }; + + // For each edge in the basic chunk graph + /** + * @param {TODO} dep the dependency used for filtering + * @returns {boolean} used to filter "edges" (aka Dependencies) that were pointing + * to modules that are already available. Also filters circular dependencies in the chunks graph + */ + const filterFn = dep => { + const depChunkGroup = dep.chunkGroup; + if (blocksWithNestedBlocks.has(dep.block)) return true; + if (areModulesAvailable(depChunkGroup, newAvailableModules)) return false; // break all modules are already available + return true; + }; + + /** @type {Map<ChunkGroup, Set<Module>>} */ + const minAvailableModulesMap = new Map(); + + // Iterative traversing of the basic chunk graph + while (queue2.length) { + const queueItem = queue2.dequeue(); + chunkGroup = queueItem.chunkGroup; + availableModules = queueItem.availableModules; + + // 1. Get minimal available modules + // It doesn't make sense to traverse a chunk again with more available modules. + // This step calculates the minimal available modules and skips traversal when + // the list didn't shrink. + let minAvailableModules = minAvailableModulesMap.get(chunkGroup); + if (minAvailableModules === undefined) { + minAvailableModulesMap.set(chunkGroup, new Set(availableModules)); + } else { + let deletedModules = false; + for (const m of minAvailableModules) { + if (!availableModules.has(m)) { + minAvailableModules.delete(m); + deletedModules = true; + } + } + if (!deletedModules) continue; + availableModules = minAvailableModules; + } + + // 2. Get the edges at this point of the graph + const deps = chunkDependencies.get(chunkGroup); + if (!deps) continue; + if (deps.length === 0) continue; + + // 3. Create a new Set of available modules at this points + newAvailableModules = new Set(availableModules); + for (const chunk of chunkGroup.chunks) { + for (const m of chunk.modulesIterable) { + newAvailableModules.add(m); + } + } + + // 4. Filter edges with available modules + const filteredDeps = deps.filter(filterFn); + + // 5. Foreach remaining edge + const nextChunkGroups = new Set(); + for (let i = 0; i < filteredDeps.length; i++) { + const dep = filteredDeps[i]; + const depChunkGroup = dep.chunkGroup; + const depBlock = dep.block; + + // 6. Connect block with chunk + GraphHelpers.connectDependenciesBlockAndChunkGroup( + depBlock, + depChunkGroup + ); + + // 7. Connect chunk with parent + GraphHelpers.connectChunkGroupParentAndChild(chunkGroup, depChunkGroup); + + nextChunkGroups.add(depChunkGroup); + } + + // 8. Enqueue further traversal + for (const nextChunkGroup of nextChunkGroups) { + queue2.enqueue({ + chunkGroup: nextChunkGroup, + availableModules: newAvailableModules + }); + } + } + + // Remove all unconnected chunk groups + for (const chunkGroup of allCreatedChunkGroups) { + if (chunkGroup.getNumberOfParents() === 0) { + for (const chunk of chunkGroup.chunks) { + const idx = this.chunks.indexOf(chunk); + if (idx >= 0) this.chunks.splice(idx, 1); + chunk.remove("unconnected"); + } + chunkGroup.remove("unconnected"); + } + } + } + + /** + * + * @param {Module} module module relationship for removal + * @param {DependenciesBlockLike} block //TODO: good description + * @returns {void} + */ + removeReasonsOfDependencyBlock(module, block) { + const iteratorDependency = d => { + if (!d.module) { + return; + } + if (d.module.removeReason(module, d)) { + for (const chunk of d.module.chunksIterable) { + this.patchChunksAfterReasonRemoval(d.module, chunk); + } + } + }; + + if (block.blocks) { + iterationOfArrayCallback(block.blocks, block => + this.removeReasonsOfDependencyBlock(module, block) + ); + } + + if (block.dependencies) { + iterationOfArrayCallback(block.dependencies, iteratorDependency); + } + + if (block.variables) { + iterationBlockVariable(block.variables, iteratorDependency); + } + } + + /** + * @param {Module} module module to patch tie + * @param {Chunk} chunk chunk to patch tie + * @returns {void} + */ + patchChunksAfterReasonRemoval(module, chunk) { + if (!module.hasReasons()) { + this.removeReasonsOfDependencyBlock(module, module); + } + if (!module.hasReasonForChunk(chunk)) { + if (module.removeChunk(chunk)) { + this.removeChunkFromDependencies(module, chunk); + } + } + } + + /** + * + * @param {DependenciesBlock} block block tie for Chunk + * @param {Chunk} chunk chunk to remove from dep + * @returns {void} + */ + removeChunkFromDependencies(block, chunk) { + const iteratorDependency = d => { + if (!d.module) { + return; + } + this.patchChunksAfterReasonRemoval(d.module, chunk); + }; + + const blocks = block.blocks; + for (let indexBlock = 0; indexBlock < blocks.length; indexBlock++) { + const asyncBlock = blocks[indexBlock]; + // Grab all chunks from the first Block's AsyncDepBlock + const chunks = asyncBlock.chunkGroup.chunks; + // For each chunk in chunkGroup + for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { + const iteratedChunk = chunks[indexChunk]; + asyncBlock.chunkGroup.removeChunk(iteratedChunk); + asyncBlock.chunkGroup.removeParent(iteratedChunk); + // Recurse + this.removeChunkFromDependencies(block, iteratedChunk); + } + } + + if (block.dependencies) { + iterationOfArrayCallback(block.dependencies, iteratorDependency); + } + + if (block.variables) { + iterationBlockVariable(block.variables, iteratorDependency); + } + } + + applyModuleIds() { + const unusedIds = []; + let nextFreeModuleId = 0; + const usedIds = new Set(); + if (this.usedModuleIds) { + for (const id of this.usedModuleIds) { + usedIds.add(id); + } + } + + const modules1 = this.modules; + for (let indexModule1 = 0; indexModule1 < modules1.length; indexModule1++) { + const module1 = modules1[indexModule1]; + if (module1.id !== null) { + usedIds.add(module1.id); + } + } + + if (usedIds.size > 0) { + let usedIdMax = -1; + for (const usedIdKey of usedIds) { + if (typeof usedIdKey !== "number") { + continue; + } + + usedIdMax = Math.max(usedIdMax, usedIdKey); + } + + let lengthFreeModules = (nextFreeModuleId = usedIdMax + 1); + + while (lengthFreeModules--) { + if (!usedIds.has(lengthFreeModules)) { + unusedIds.push(lengthFreeModules); + } + } + } + + const modules2 = this.modules; + for (let indexModule2 = 0; indexModule2 < modules2.length; indexModule2++) { + const module2 = modules2[indexModule2]; + if (module2.id === null) { + if (unusedIds.length > 0) { + module2.id = unusedIds.pop(); + } else { + module2.id = nextFreeModuleId++; + } + } + } + } + + applyChunkIds() { + /** @type {Set<number>} */ + const usedIds = new Set(); + + // Get used ids from usedChunkIds property (i. e. from records) + if (this.usedChunkIds) { + for (const id of this.usedChunkIds) { + if (typeof id !== "number") { + continue; + } + + usedIds.add(id); + } + } + + // Get used ids from existing chunks + const chunks = this.chunks; + for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { + const chunk = chunks[indexChunk]; + const usedIdValue = chunk.id; + + if (typeof usedIdValue !== "number") { + continue; + } + + usedIds.add(usedIdValue); + } + + // Calculate maximum assigned chunk id + let nextFreeChunkId = -1; + for (const id of usedIds) { + nextFreeChunkId = Math.max(nextFreeChunkId, id); + } + nextFreeChunkId++; + + // Determine free chunk ids from 0 to maximum + /** @type {number[]} */ + const unusedIds = []; + if (nextFreeChunkId > 0) { + let index = nextFreeChunkId; + while (index--) { + if (!usedIds.has(index)) { + unusedIds.push(index); + } + } + } + + // Assign ids to chunk which has no id + for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { + const chunk = chunks[indexChunk]; + if (chunk.id === null) { + if (unusedIds.length > 0) { + chunk.id = unusedIds.pop(); + } else { + chunk.id = nextFreeChunkId++; + } + } + if (!chunk.ids) { + chunk.ids = [chunk.id]; + } + } + } + + sortItemsWithModuleIds() { + this.modules.sort(byIdOrIdentifier); + + const modules = this.modules; + for (let indexModule = 0; indexModule < modules.length; indexModule++) { + modules[indexModule].sortItems(false); + } + + const chunks = this.chunks; + for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { + chunks[indexChunk].sortItems(); + } + } + + sortItemsWithChunkIds() { + for (const chunkGroup of this.chunkGroups) { + chunkGroup.sortItems(); + } + + this.chunks.sort(byId); + + for ( + let indexModule = 0; + indexModule < this.modules.length; + indexModule++ + ) { + this.modules[indexModule].sortItems(true); + } + + const chunks = this.chunks; + for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { + chunks[indexChunk].sortItems(); + } + + /** + * Used to sort errors and warnings in compilation. this.warnings, and + * this.errors contribute to the compilation hash and therefore should be + * updated whenever other references (having a chunk id) are sorted. This preserves the hash + * integrity + * + * @param {WebpackError} a first WebpackError instance (including subclasses) + * @param {WebpackError} b second WebpackError instance (including subclasses) + * @returns {-1|0|1} sort order index + */ + const byMessage = (a, b) => { + const ma = `${a.message}`; + const mb = `${b.message}`; + if (ma < mb) return -1; + if (mb < ma) return 1; + return 0; + }; + + this.errors.sort(byMessage); + this.warnings.sort(byMessage); + this.children.sort(byNameOrHash); + } + + summarizeDependencies() { + this.fileDependencies = new SortableSet(this.compilationDependencies); + this.contextDependencies = new SortableSet(); + this.missingDependencies = new SortableSet(); + + for ( + let indexChildren = 0; + indexChildren < this.children.length; + indexChildren++ + ) { + const child = this.children[indexChildren]; + + addAllToSet(this.fileDependencies, child.fileDependencies); + addAllToSet(this.contextDependencies, child.contextDependencies); + addAllToSet(this.missingDependencies, child.missingDependencies); + } + + for ( + let indexModule = 0; + indexModule < this.modules.length; + indexModule++ + ) { + const module = this.modules[indexModule]; + + if (module.buildInfo.fileDependencies) { + addAllToSet(this.fileDependencies, module.buildInfo.fileDependencies); + } + if (module.buildInfo.contextDependencies) { + addAllToSet( + this.contextDependencies, + module.buildInfo.contextDependencies + ); + } + } + for (const error of this.errors) { + if ( + typeof error.missing === "object" && + error.missing && + error.missing[Symbol.iterator] + ) { + addAllToSet(this.missingDependencies, error.missing); + } + } + this.fileDependencies.sort(); + this.contextDependencies.sort(); + this.missingDependencies.sort(); + } + + createHash() { + const outputOptions = this.outputOptions; + const hashFunction = outputOptions.hashFunction; + const hashDigest = outputOptions.hashDigest; + const hashDigestLength = outputOptions.hashDigestLength; + const hash = createHash(hashFunction); + if (outputOptions.hashSalt) { + hash.update(outputOptions.hashSalt); + } + this.mainTemplate.updateHash(hash); + this.chunkTemplate.updateHash(hash); + for (const key of Object.keys(this.moduleTemplates).sort()) { + this.moduleTemplates[key].updateHash(hash); + } + for (const child of this.children) { + hash.update(child.hash); + } + for (const warning of this.warnings) { + hash.update(`${warning.message}`); + } + for (const error of this.errors) { + hash.update(`${error.message}`); + } + const modules = this.modules; + for (let i = 0; i < modules.length; i++) { + const module = modules[i]; + const moduleHash = createHash(hashFunction); + module.updateHash(moduleHash); + module.hash = moduleHash.digest(hashDigest); + module.renderedHash = module.hash.substr(0, hashDigestLength); + } + // clone needed as sort below is inplace mutation + const chunks = this.chunks.slice(); + /** + * sort here will bring all "falsy" values to the beginning + * this is needed as the "hasRuntime()" chunks are dependent on the + * hashes of the non-runtime chunks. + */ + chunks.sort((a, b) => { + const aEntry = a.hasRuntime(); + const bEntry = b.hasRuntime(); + if (aEntry && !bEntry) return 1; + if (!aEntry && bEntry) return -1; + return byId(a, b); + }); + for (let i = 0; i < chunks.length; i++) { + const chunk = chunks[i]; + const chunkHash = createHash(hashFunction); + if (outputOptions.hashSalt) { + chunkHash.update(outputOptions.hashSalt); + } + chunk.updateHash(chunkHash); + const template = chunk.hasRuntime() + ? this.mainTemplate + : this.chunkTemplate; + template.updateHashForChunk( + chunkHash, + chunk, + this.moduleTemplates.javascript, + this.dependencyTemplates + ); + this.hooks.chunkHash.call(chunk, chunkHash); + chunk.hash = chunkHash.digest(hashDigest); + hash.update(chunk.hash); + chunk.renderedHash = chunk.hash.substr(0, hashDigestLength); + this.hooks.contentHash.call(chunk); + } + this.fullHash = hash.digest(hashDigest); + this.hash = this.fullHash.substr(0, hashDigestLength); + } + + /** + * @param {string} update extra information + * @returns {void} + */ + modifyHash(update) { + const outputOptions = this.outputOptions; + const hashFunction = outputOptions.hashFunction; + const hashDigest = outputOptions.hashDigest; + const hashDigestLength = outputOptions.hashDigestLength; + const hash = createHash(hashFunction); + hash.update(this.fullHash); + hash.update(update); + this.fullHash = hash.digest(hashDigest); + this.hash = this.fullHash.substr(0, hashDigestLength); + } + + createModuleAssets() { + for (let i = 0; i < this.modules.length; i++) { + const module = this.modules[i]; + if (module.buildInfo.assets) { + for (const assetName of Object.keys(module.buildInfo.assets)) { + const fileName = this.getPath(assetName); + this.assets[fileName] = module.buildInfo.assets[assetName]; + this.hooks.moduleAsset.call(module, fileName); + } + } + } + } + + createChunkAssets() { + const outputOptions = this.outputOptions; + const cachedSourceMap = new Map(); + /** @type {Map<string, {hash: string, source: Source, chunk: Chunk}>} */ + const alreadyWrittenFiles = new Map(); + for (let i = 0; i < this.chunks.length; i++) { + const chunk = this.chunks[i]; + chunk.files = []; + let source; + let file; + let filenameTemplate; + try { + const template = chunk.hasRuntime() + ? this.mainTemplate + : this.chunkTemplate; + const manifest = template.getRenderManifest({ + chunk, + hash: this.hash, + fullHash: this.fullHash, + outputOptions, + moduleTemplates: this.moduleTemplates, + dependencyTemplates: this.dependencyTemplates + }); // [{ render(), filenameTemplate, pathOptions, identifier, hash }] + for (const fileManifest of manifest) { + const cacheName = fileManifest.identifier; + const usedHash = fileManifest.hash; + filenameTemplate = fileManifest.filenameTemplate; + file = this.getPath(filenameTemplate, fileManifest.pathOptions); + + // check if the same filename was already written by another chunk + const alreadyWritten = alreadyWrittenFiles.get(file); + if (alreadyWritten !== undefined) { + if (alreadyWritten.hash === usedHash) { + if (this.cache) { + this.cache[cacheName] = { + hash: usedHash, + source: alreadyWritten.source + }; + } + chunk.files.push(file); + this.hooks.chunkAsset.call(chunk, file); + continue; + } else { + throw new Error( + `Conflict: Multiple chunks emit assets to the same filename ${file}` + + ` (chunks ${alreadyWritten.chunk.id} and ${chunk.id})` + ); + } + } + if ( + this.cache && + this.cache[cacheName] && + this.cache[cacheName].hash === usedHash + ) { + source = this.cache[cacheName].source; + } else { + source = fileManifest.render(); + // Ensure that source is a cached source to avoid additional cost because of repeated access + if (!(source instanceof CachedSource)) { + const cacheEntry = cachedSourceMap.get(source); + if (cacheEntry) { + source = cacheEntry; + } else { + const cachedSource = new CachedSource(source); + cachedSourceMap.set(source, cachedSource); + source = cachedSource; + } + } + if (this.cache) { + this.cache[cacheName] = { + hash: usedHash, + source + }; + } + } + if (this.assets[file] && this.assets[file] !== source) { + throw new Error( + `Conflict: Multiple assets emit to the same filename ${file}` + ); + } + this.assets[file] = source; + chunk.files.push(file); + this.hooks.chunkAsset.call(chunk, file); + alreadyWrittenFiles.set(file, { + hash: usedHash, + source, + chunk + }); + } + } catch (err) { + this.errors.push( + new ChunkRenderError(chunk, file || filenameTemplate, err) + ); + } + } + } + + /** + * @param {string} filename used to get asset path with hash + * @param {TODO=} data // TODO: figure out this param type + * @returns {string} interpolated path + */ + getPath(filename, data) { + data = data || {}; + data.hash = data.hash || this.hash; + return this.mainTemplate.getAssetPath(filename, data); + } + + /** + * This function allows you to run another instance of webpack inside of webpack however as + * a child with different settings and configurations (if desired) applied. It copies all hooks, plugins + * from parent (or top level compiler) and creates a child Compilation + * + * @param {string} name name of the child compiler + * @param {TODO} outputOptions // Need to convert config schema to types for this + * @param {Plugin[]} plugins webpack plugins that will be applied + * @returns {Compiler} creates a child Compiler instance + */ + createChildCompiler(name, outputOptions, plugins) { + const idx = this.childrenCounters[name] || 0; + this.childrenCounters[name] = idx + 1; + return this.compiler.createChildCompiler( + this, + name, + idx, + outputOptions, + plugins + ); + } + + checkConstraints() { + /** @type {Set<number|string>} */ + const usedIds = new Set(); + + const modules = this.modules; + for (let indexModule = 0; indexModule < modules.length; indexModule++) { + const moduleId = modules[indexModule].id; + if (moduleId === null) continue; + if (usedIds.has(moduleId)) { + throw new Error(`checkConstraints: duplicate module id ${moduleId}`); + } + usedIds.add(moduleId); + } + + const chunks = this.chunks; + for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { + const chunk = chunks[indexChunk]; + if (chunks.indexOf(chunk) !== indexChunk) { + throw new Error( + `checkConstraints: duplicate chunk in compilation ${chunk.debugId}` + ); + } + } + + for (const chunkGroup of this.chunkGroups) { + chunkGroup.checkConstraints(); + } + } +} + +// TODO remove in webpack 5 +Compilation.prototype.applyPlugins = util.deprecate( + /** + * @deprecated + * @param {string} name Name + * @param {any[]} args Other arguments + * @returns {void} + * @this {Compilation} + */ + function(name, ...args) { + this.hooks[ + name.replace(/[- ]([a-z])/g, match => match[1].toUpperCase()) + ].call(...args); + }, + "Compilation.applyPlugins is deprecated. Use new API on `.hooks` instead" +); + +// TODO remove in webpack 5 +Object.defineProperty(Compilation.prototype, "moduleTemplate", { + configurable: false, + get: util.deprecate( + /** + * @deprecated + * @this {Compilation} + * @returns {TODO} module template + */ + function() { + return this.moduleTemplates.javascript; + }, + "Compilation.moduleTemplate: Use Compilation.moduleTemplates.javascript instead" + ), + set: util.deprecate( + /** + * @deprecated + * @param {ModuleTemplate} value Template value + * @this {Compilation} + * @returns {void} + */ + function(value) { + this.moduleTemplates.javascript = value; + }, + "Compilation.moduleTemplate: Use Compilation.moduleTemplates.javascript instead." + ) +}); + +module.exports = Compilation; diff --git a/node_modules/webpack/lib/Compiler.js b/node_modules/webpack/lib/Compiler.js index 4c7e02b4e..bf7338fca 100644 --- a/node_modules/webpack/lib/Compiler.js +++ b/node_modules/webpack/lib/Compiler.js @@ -1,519 +1,561 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const path = require("path");
-const Tapable = require("tapable");
-const util = require("util");
-
-const Compilation = require("./Compilation");
-const Stats = require("./Stats");
-const NormalModuleFactory = require("./NormalModuleFactory");
-const ContextModuleFactory = require("./ContextModuleFactory");
-
-const makePathsRelative = require("./util/identifier").makePathsRelative;
-
-class Watching {
- constructor(compiler, watchOptions, handler) {
- this.startTime = null;
- this.invalid = false;
- this.handler = handler;
- this.callbacks = [];
- this.closed = false;
- if(typeof watchOptions === "number") {
- this.watchOptions = {
- aggregateTimeout: watchOptions
- };
- } else if(watchOptions && typeof watchOptions === "object") {
- this.watchOptions = Object.assign({}, watchOptions);
- } else {
- this.watchOptions = {};
- }
- this.watchOptions.aggregateTimeout = this.watchOptions.aggregateTimeout || 200;
- this.compiler = compiler;
- this.running = true;
- this.compiler.readRecords(err => {
- if(err) return this._done(err);
-
- this._go();
- });
- }
-
- _go() {
- this.startTime = Date.now();
- this.running = true;
- this.invalid = false;
- this.compiler.applyPluginsAsync("watch-run", this, err => {
- if(err) return this._done(err);
- const onCompiled = (err, compilation) => {
- if(err) return this._done(err);
- if(this.invalid) return this._done();
-
- if(this.compiler.applyPluginsBailResult("should-emit", compilation) === false) {
- return this._done(null, compilation);
- }
-
- this.compiler.emitAssets(compilation, err => {
- if(err) return this._done(err);
- if(this.invalid) return this._done();
-
- this.compiler.emitRecords(err => {
- if(err) return this._done(err);
-
- if(compilation.applyPluginsBailResult("need-additional-pass")) {
- compilation.needAdditionalPass = true;
-
- const stats = new Stats(compilation);
- stats.startTime = this.startTime;
- stats.endTime = Date.now();
- this.compiler.applyPlugins("done", stats);
-
- this.compiler.applyPluginsAsync("additional-pass", err => {
- if(err) return this._done(err);
- this.compiler.compile(onCompiled);
- });
- return;
- }
- return this._done(null, compilation);
- });
- });
- };
- this.compiler.compile(onCompiled);
- });
- }
-
- _getStats(compilation) {
- const stats = new Stats(compilation);
- stats.startTime = this.startTime;
- stats.endTime = Date.now();
- return stats;
- }
-
- _done(err, compilation) {
- this.running = false;
- if(this.invalid) return this._go();
-
- const stats = compilation ? this._getStats(compilation) : null;
- if(err) {
- this.compiler.applyPlugins("failed", err);
- this.handler(err, stats);
- return;
- }
-
- this.compiler.applyPlugins("done", stats);
- this.handler(null, stats);
- if(!this.closed) {
- this.watch(compilation.fileDependencies, compilation.contextDependencies, compilation.missingDependencies);
- }
- this.callbacks.forEach(cb => cb());
- this.callbacks.length = 0;
- }
-
- watch(files, dirs, missing) {
- this.pausedWatcher = null;
- this.watcher = this.compiler.watchFileSystem.watch(files, dirs, missing, this.startTime, this.watchOptions, (err, filesModified, contextModified, missingModified, fileTimestamps, contextTimestamps) => {
- this.pausedWatcher = this.watcher;
- this.watcher = null;
- if(err) return this.handler(err);
-
- this.compiler.fileTimestamps = fileTimestamps;
- this.compiler.contextTimestamps = contextTimestamps;
- this.invalidate();
- }, (fileName, changeTime) => {
- this.compiler.applyPlugins("invalid", fileName, changeTime);
- });
- }
-
- invalidate(callback) {
- if(callback) {
- this.callbacks.push(callback);
- }
- if(this.watcher) {
- this.pausedWatcher = this.watcher;
- this.watcher.pause();
- this.watcher = null;
- }
- if(this.running) {
- this.invalid = true;
- return false;
- } else {
- this._go();
- }
- }
-
- close(callback) {
- if(callback === undefined) callback = function() {};
-
- this.closed = true;
- if(this.watcher) {
- this.watcher.close();
- this.watcher = null;
- }
- if(this.pausedWatcher) {
- this.pausedWatcher.close();
- this.pausedWatcher = null;
- }
- if(this.running) {
- this.invalid = true;
- this._done = () => {
- this.compiler.applyPlugins("watch-close");
- callback();
- };
- } else {
- this.compiler.applyPlugins("watch-close");
- callback();
- }
- }
-}
-
-class Compiler extends Tapable {
- constructor() {
- super();
- this.outputPath = "";
- this.outputFileSystem = null;
- this.inputFileSystem = null;
-
- this.recordsInputPath = null;
- this.recordsOutputPath = null;
- this.records = {};
-
- this.fileTimestamps = {};
- this.contextTimestamps = {};
-
- this.resolvers = {
- normal: null,
- loader: null,
- context: null
- };
- this.parser = {
- plugin: util.deprecate(
- (hook, fn) => {
- this.plugin("compilation", (compilation, data) => {
- data.normalModuleFactory.plugin("parser", parser => {
- parser.plugin(hook, fn);
- });
- });
- },
- "webpack: Using compiler.parser is deprecated.\n" +
- "Use compiler.plugin(\"compilation\", function(compilation, data) {\n data.normalModuleFactory.plugin(\"parser\", function(parser, options) { parser.plugin(/* ... */); });\n}); instead. "
- ),
- apply: util.deprecate(
- () => {
- const args = arguments;
- this.plugin("compilation", (compilation, data) => {
- data.normalModuleFactory.plugin("parser", parser => {
- parser.apply.apply(parser, args);
- });
- });
- },
- "webpack: Using compiler.parser is deprecated.\n" +
- "Use compiler.plugin(\"compilation\", function(compilation, data) {\n data.normalModuleFactory.plugin(\"parser\", function(parser, options) { parser.apply(/* ... */); });\n}); instead. "
- )
- };
-
- this.options = {};
- }
-
- watch(watchOptions, handler) {
- this.fileTimestamps = {};
- this.contextTimestamps = {};
- const watching = new Watching(this, watchOptions, handler);
- return watching;
- }
-
- run(callback) {
- const startTime = Date.now();
-
- const onCompiled = (err, compilation) => {
- if(err) return callback(err);
-
- if(this.applyPluginsBailResult("should-emit", compilation) === false) {
- const stats = new Stats(compilation);
- stats.startTime = startTime;
- stats.endTime = Date.now();
- this.applyPlugins("done", stats);
- return callback(null, stats);
- }
-
- this.emitAssets(compilation, err => {
- if(err) return callback(err);
-
- if(compilation.applyPluginsBailResult("need-additional-pass")) {
- compilation.needAdditionalPass = true;
-
- const stats = new Stats(compilation);
- stats.startTime = startTime;
- stats.endTime = Date.now();
- this.applyPlugins("done", stats);
-
- this.applyPluginsAsync("additional-pass", err => {
- if(err) return callback(err);
- this.compile(onCompiled);
- });
- return;
- }
-
- this.emitRecords(err => {
- if(err) return callback(err);
-
- const stats = new Stats(compilation);
- stats.startTime = startTime;
- stats.endTime = Date.now();
- this.applyPlugins("done", stats);
- return callback(null, stats);
- });
- });
- };
-
- this.applyPluginsAsync("before-run", this, err => {
- if(err) return callback(err);
-
- this.applyPluginsAsync("run", this, err => {
- if(err) return callback(err);
-
- this.readRecords(err => {
- if(err) return callback(err);
-
- this.compile(onCompiled);
- });
- });
- });
- }
-
- runAsChild(callback) {
- this.compile((err, compilation) => {
- if(err) return callback(err);
-
- this.parentCompilation.children.push(compilation);
- Object.keys(compilation.assets).forEach(name => {
- this.parentCompilation.assets[name] = compilation.assets[name];
- });
-
- const entries = Object.keys(compilation.entrypoints).map(name => {
- return compilation.entrypoints[name].chunks;
- }).reduce((array, chunks) => {
- return array.concat(chunks);
- }, []);
-
- return callback(null, entries, compilation);
- });
- }
-
- purgeInputFileSystem() {
- if(this.inputFileSystem && this.inputFileSystem.purge)
- this.inputFileSystem.purge();
- }
-
- emitAssets(compilation, callback) {
- let outputPath;
-
- const emitFiles = (err) => {
- if(err) return callback(err);
-
- require("async").forEach(Object.keys(compilation.assets), (file, callback) => {
-
- let targetFile = file;
- const queryStringIdx = targetFile.indexOf("?");
- if(queryStringIdx >= 0) {
- targetFile = targetFile.substr(0, queryStringIdx);
- }
-
- const writeOut = (err) => {
- if(err) return callback(err);
- const targetPath = this.outputFileSystem.join(outputPath, targetFile);
- const source = compilation.assets[file];
- if(source.existsAt === targetPath) {
- source.emitted = false;
- return callback();
- }
- let content = source.source();
-
- if(!Buffer.isBuffer(content)) {
- content = new Buffer(content, "utf8"); // eslint-disable-line
- }
-
- source.existsAt = targetPath;
- source.emitted = true;
- this.outputFileSystem.writeFile(targetPath, content, callback);
- };
-
- if(targetFile.match(/\/|\\/)) {
- const dir = path.dirname(targetFile);
- this.outputFileSystem.mkdirp(this.outputFileSystem.join(outputPath, dir), writeOut);
- } else writeOut();
-
- }, err => {
- if(err) return callback(err);
-
- afterEmit.call(this);
- });
- };
-
- this.applyPluginsAsync("emit", compilation, err => {
- if(err) return callback(err);
- outputPath = compilation.getPath(this.outputPath);
- this.outputFileSystem.mkdirp(outputPath, emitFiles);
- });
-
- function afterEmit() {
- this.applyPluginsAsyncSeries1("after-emit", compilation, err => {
- if(err) return callback(err);
-
- return callback();
- });
- }
-
- }
-
- emitRecords(callback) {
- if(!this.recordsOutputPath) return callback();
- const idx1 = this.recordsOutputPath.lastIndexOf("/");
- const idx2 = this.recordsOutputPath.lastIndexOf("\\");
- let recordsOutputPathDirectory = null;
- if(idx1 > idx2) recordsOutputPathDirectory = this.recordsOutputPath.substr(0, idx1);
- if(idx1 < idx2) recordsOutputPathDirectory = this.recordsOutputPath.substr(0, idx2);
- if(!recordsOutputPathDirectory) return writeFile.call(this);
- this.outputFileSystem.mkdirp(recordsOutputPathDirectory, err => {
- if(err) return callback(err);
- writeFile.call(this);
- });
-
- function writeFile() {
- this.outputFileSystem.writeFile(this.recordsOutputPath, JSON.stringify(this.records, undefined, 2), callback);
- }
- }
-
- readRecords(callback) {
- if(!this.recordsInputPath) {
- this.records = {};
- return callback();
- }
- this.inputFileSystem.stat(this.recordsInputPath, err => {
- // It doesn't exist
- // We can ignore this.
- if(err) return callback();
-
- this.inputFileSystem.readFile(this.recordsInputPath, (err, content) => {
- if(err) return callback(err);
-
- try {
- this.records = JSON.parse(content.toString("utf-8"));
- } catch(e) {
- e.message = "Cannot parse records: " + e.message;
- return callback(e);
- }
-
- return callback();
- });
- });
- }
-
- createChildCompiler(compilation, compilerName, compilerIndex, outputOptions, plugins) {
- const childCompiler = new Compiler();
- if(Array.isArray(plugins)) {
- plugins.forEach(plugin => childCompiler.apply(plugin));
- }
- for(const name in this._plugins) {
- if(["make", "compile", "emit", "after-emit", "invalid", "done", "this-compilation"].indexOf(name) < 0)
- childCompiler._plugins[name] = this._plugins[name].slice();
- }
- childCompiler.name = compilerName;
- childCompiler.outputPath = this.outputPath;
- childCompiler.inputFileSystem = this.inputFileSystem;
- childCompiler.outputFileSystem = null;
- childCompiler.resolvers = this.resolvers;
- childCompiler.fileTimestamps = this.fileTimestamps;
- childCompiler.contextTimestamps = this.contextTimestamps;
-
- const relativeCompilerName = makePathsRelative(this.context, compilerName);
- if(!this.records[relativeCompilerName]) this.records[relativeCompilerName] = [];
- if(this.records[relativeCompilerName][compilerIndex])
- childCompiler.records = this.records[relativeCompilerName][compilerIndex];
- else
- this.records[relativeCompilerName].push(childCompiler.records = {});
-
- childCompiler.options = Object.create(this.options);
- childCompiler.options.output = Object.create(childCompiler.options.output);
- for(const name in outputOptions) {
- childCompiler.options.output[name] = outputOptions[name];
- }
- childCompiler.parentCompilation = compilation;
-
- compilation.applyPlugins("child-compiler", childCompiler, compilerName, compilerIndex);
-
- return childCompiler;
- }
-
- isChild() {
- return !!this.parentCompilation;
- }
-
- createCompilation() {
- return new Compilation(this);
- }
-
- newCompilation(params) {
- const compilation = this.createCompilation();
- compilation.fileTimestamps = this.fileTimestamps;
- compilation.contextTimestamps = this.contextTimestamps;
- compilation.name = this.name;
- compilation.records = this.records;
- compilation.compilationDependencies = params.compilationDependencies;
- this.applyPlugins("this-compilation", compilation, params);
- this.applyPlugins("compilation", compilation, params);
- return compilation;
- }
-
- createNormalModuleFactory() {
- const normalModuleFactory = new NormalModuleFactory(this.options.context, this.resolvers, this.options.module || {});
- this.applyPlugins("normal-module-factory", normalModuleFactory);
- return normalModuleFactory;
- }
-
- createContextModuleFactory() {
- const contextModuleFactory = new ContextModuleFactory(this.resolvers, this.inputFileSystem);
- this.applyPlugins("context-module-factory", contextModuleFactory);
- return contextModuleFactory;
- }
-
- newCompilationParams() {
- const params = {
- normalModuleFactory: this.createNormalModuleFactory(),
- contextModuleFactory: this.createContextModuleFactory(),
- compilationDependencies: []
- };
- return params;
- }
-
- compile(callback) {
- const params = this.newCompilationParams();
- this.applyPluginsAsync("before-compile", params, err => {
- if(err) return callback(err);
-
- this.applyPlugins("compile", params);
-
- const compilation = this.newCompilation(params);
-
- this.applyPluginsParallel("make", compilation, err => {
- if(err) return callback(err);
-
- compilation.finish();
-
- compilation.seal(err => {
- if(err) return callback(err);
-
- this.applyPluginsAsync("after-compile", compilation, err => {
- if(err) return callback(err);
-
- return callback(null, compilation);
- });
- });
- });
- });
- }
-}
-
-Compiler.Watching = Watching;
-module.exports = Compiler;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const parseJson = require("json-parse-better-errors"); +const asyncLib = require("neo-async"); +const path = require("path"); +const util = require("util"); +const { + Tapable, + SyncHook, + SyncBailHook, + AsyncParallelHook, + AsyncSeriesHook +} = require("tapable"); + +const Compilation = require("./Compilation"); +const Stats = require("./Stats"); +const Watching = require("./Watching"); +const NormalModuleFactory = require("./NormalModuleFactory"); +const ContextModuleFactory = require("./ContextModuleFactory"); +const ResolverFactory = require("./ResolverFactory"); + +const RequestShortener = require("./RequestShortener"); +const { makePathsRelative } = require("./util/identifier"); +const ConcurrentCompilationError = require("./ConcurrentCompilationError"); + +/** + * @typedef {Object} CompilationParams + * @property {NormalModuleFactory} normalModuleFactory + * @property {ContextModuleFactory} contextModuleFactory + * @property {Set<string>} compilationDependencies + */ + +/** @typedef {string|string[]} EntryValues */ +/** @typedef {Record<string, EntryValues>} EntryOptionValues */ + +/** + * @callback EntryOptionValuesFunction + * @returns {EntryOptionValues | EntryValues} the computed value + */ + +/** @typedef {EntryOptionValuesFunction | EntryOptionValues | EntryValues} EntryOptions */ + +class Compiler extends Tapable { + constructor(context) { + super(); + this.hooks = { + /** @type {SyncBailHook<Compilation>} */ + shouldEmit: new SyncBailHook(["compilation"]), + /** @type {AsyncSeriesHook<Stats>} */ + done: new AsyncSeriesHook(["stats"]), + /** @type {AsyncSeriesHook<>} */ + additionalPass: new AsyncSeriesHook([]), + /** @type {AsyncSeriesHook<Compiler>} */ + beforeRun: new AsyncSeriesHook(["compiler"]), + /** @type {AsyncSeriesHook<Compiler>} */ + run: new AsyncSeriesHook(["compiler"]), + /** @type {AsyncSeriesHook<Compilation>} */ + emit: new AsyncSeriesHook(["compilation"]), + /** @type {AsyncSeriesHook<Compilation>} */ + afterEmit: new AsyncSeriesHook(["compilation"]), + + /** @type {SyncHook<Compilation, CompilationParams>} */ + thisCompilation: new SyncHook(["compilation", "params"]), + /** @type {SyncHook<Compilation, CompilationParams>} */ + compilation: new SyncHook(["compilation", "params"]), + /** @type {SyncHook<NormalModuleFactory>} */ + normalModuleFactory: new SyncHook(["normalModuleFactory"]), + /** @type {SyncHook<ContextModuleFactory>} */ + contextModuleFactory: new SyncHook(["contextModulefactory"]), + + /** @type {AsyncSeriesHook<CompilationParams>} */ + beforeCompile: new AsyncSeriesHook(["params"]), + /** @type {SyncHook<CompilationParams>} */ + compile: new SyncHook(["params"]), + /** @type {AsyncParallelHook<Compilation>} */ + make: new AsyncParallelHook(["compilation"]), + /** @type {AsyncSeriesHook<Compilation>} */ + afterCompile: new AsyncSeriesHook(["compilation"]), + + /** @type {AsyncSeriesHook<Compiler>} */ + watchRun: new AsyncSeriesHook(["compiler"]), + /** @type {SyncHook<Error>} */ + failed: new SyncHook(["error"]), + /** @type {SyncHook<string, string>} */ + invalid: new SyncHook(["filename", "changeTime"]), + /** @type {SyncHook} */ + watchClose: new SyncHook([]), + + // TODO the following hooks are weirdly located here + // TODO move them for webpack 5 + /** @type {SyncHook} */ + environment: new SyncHook([]), + /** @type {SyncHook} */ + afterEnvironment: new SyncHook([]), + /** @type {SyncHook<Compiler>} */ + afterPlugins: new SyncHook(["compiler"]), + /** @type {SyncHook<Compiler>} */ + afterResolvers: new SyncHook(["compiler"]), + /** @type {SyncBailHook<string, EntryOptions>} */ + entryOption: new SyncBailHook(["context", "entry"]) + }; + + this._pluginCompat.tap("Compiler", options => { + switch (options.name) { + case "additional-pass": + case "before-run": + case "run": + case "emit": + case "after-emit": + case "before-compile": + case "make": + case "after-compile": + case "watch-run": + options.async = true; + break; + } + }); + + /** @type {string=} */ + this.name = undefined; + /** @type {Compilation=} */ + this.parentCompilation = undefined; + /** @type {string} */ + this.outputPath = ""; + + this.outputFileSystem = null; + this.inputFileSystem = null; + + /** @type {string|null} */ + this.recordsInputPath = null; + /** @type {string|null} */ + this.recordsOutputPath = null; + this.records = {}; + /** @type {Map<string, number>} */ + this.fileTimestamps = new Map(); + /** @type {Map<string, number>} */ + this.contextTimestamps = new Map(); + /** @type {ResolverFactory} */ + this.resolverFactory = new ResolverFactory(); + + // TODO remove in webpack 5 + this.resolvers = { + normal: { + plugins: util.deprecate((hook, fn) => { + this.resolverFactory.plugin("resolver normal", resolver => { + resolver.plugin(hook, fn); + }); + }, "webpack: Using compiler.resolvers.normal is deprecated.\n" + 'Use compiler.resolverFactory.plugin("resolver normal", resolver => {\n resolver.plugin(/* … */);\n}); instead.'), + apply: util.deprecate((...args) => { + this.resolverFactory.plugin("resolver normal", resolver => { + resolver.apply(...args); + }); + }, "webpack: Using compiler.resolvers.normal is deprecated.\n" + 'Use compiler.resolverFactory.plugin("resolver normal", resolver => {\n resolver.apply(/* … */);\n}); instead.') + }, + loader: { + plugins: util.deprecate((hook, fn) => { + this.resolverFactory.plugin("resolver loader", resolver => { + resolver.plugin(hook, fn); + }); + }, "webpack: Using compiler.resolvers.loader is deprecated.\n" + 'Use compiler.resolverFactory.plugin("resolver loader", resolver => {\n resolver.plugin(/* … */);\n}); instead.'), + apply: util.deprecate((...args) => { + this.resolverFactory.plugin("resolver loader", resolver => { + resolver.apply(...args); + }); + }, "webpack: Using compiler.resolvers.loader is deprecated.\n" + 'Use compiler.resolverFactory.plugin("resolver loader", resolver => {\n resolver.apply(/* … */);\n}); instead.') + }, + context: { + plugins: util.deprecate((hook, fn) => { + this.resolverFactory.plugin("resolver context", resolver => { + resolver.plugin(hook, fn); + }); + }, "webpack: Using compiler.resolvers.context is deprecated.\n" + 'Use compiler.resolverFactory.plugin("resolver context", resolver => {\n resolver.plugin(/* … */);\n}); instead.'), + apply: util.deprecate((...args) => { + this.resolverFactory.plugin("resolver context", resolver => { + resolver.apply(...args); + }); + }, "webpack: Using compiler.resolvers.context is deprecated.\n" + 'Use compiler.resolverFactory.plugin("resolver context", resolver => {\n resolver.apply(/* … */);\n}); instead.') + } + }; + + this.options = {}; + + this.context = context; + + this.requestShortener = new RequestShortener(context); + + /** @type {boolean} */ + this.running = false; + } + + watch(watchOptions, handler) { + if (this.running) return handler(new ConcurrentCompilationError()); + + this.running = true; + this.fileTimestamps = new Map(); + this.contextTimestamps = new Map(); + return new Watching(this, watchOptions, handler); + } + + run(callback) { + if (this.running) return callback(new ConcurrentCompilationError()); + + const finalCallback = (err, stats) => { + this.running = false; + + if (callback !== undefined) return callback(err, stats); + }; + + const startTime = Date.now(); + + this.running = true; + + const onCompiled = (err, compilation) => { + if (err) return finalCallback(err); + + if (this.hooks.shouldEmit.call(compilation) === false) { + const stats = new Stats(compilation); + stats.startTime = startTime; + stats.endTime = Date.now(); + this.hooks.done.callAsync(stats, err => { + if (err) return finalCallback(err); + return finalCallback(null, stats); + }); + return; + } + + this.emitAssets(compilation, err => { + if (err) return finalCallback(err); + + if (compilation.hooks.needAdditionalPass.call()) { + compilation.needAdditionalPass = true; + + const stats = new Stats(compilation); + stats.startTime = startTime; + stats.endTime = Date.now(); + this.hooks.done.callAsync(stats, err => { + if (err) return finalCallback(err); + + this.hooks.additionalPass.callAsync(err => { + if (err) return finalCallback(err); + this.compile(onCompiled); + }); + }); + return; + } + + this.emitRecords(err => { + if (err) return finalCallback(err); + + const stats = new Stats(compilation); + stats.startTime = startTime; + stats.endTime = Date.now(); + this.hooks.done.callAsync(stats, err => { + if (err) return finalCallback(err); + return finalCallback(null, stats); + }); + }); + }); + }; + + this.hooks.beforeRun.callAsync(this, err => { + if (err) return finalCallback(err); + + this.hooks.run.callAsync(this, err => { + if (err) return finalCallback(err); + + this.readRecords(err => { + if (err) return finalCallback(err); + + this.compile(onCompiled); + }); + }); + }); + } + + runAsChild(callback) { + this.compile((err, compilation) => { + if (err) return callback(err); + + this.parentCompilation.children.push(compilation); + for (const name of Object.keys(compilation.assets)) { + this.parentCompilation.assets[name] = compilation.assets[name]; + } + + const entries = Array.from( + compilation.entrypoints.values(), + ep => ep.chunks + ).reduce((array, chunks) => { + return array.concat(chunks); + }, []); + + return callback(null, entries, compilation); + }); + } + + purgeInputFileSystem() { + if (this.inputFileSystem && this.inputFileSystem.purge) { + this.inputFileSystem.purge(); + } + } + + emitAssets(compilation, callback) { + let outputPath; + + const emitFiles = err => { + if (err) return callback(err); + + asyncLib.forEach( + compilation.assets, + (source, file, callback) => { + let targetFile = file; + const queryStringIdx = targetFile.indexOf("?"); + if (queryStringIdx >= 0) { + targetFile = targetFile.substr(0, queryStringIdx); + } + + const writeOut = err => { + if (err) return callback(err); + const targetPath = this.outputFileSystem.join( + outputPath, + targetFile + ); + if (source.existsAt === targetPath) { + source.emitted = false; + return callback(); + } + let content = source.source(); + + if (!Buffer.isBuffer(content)) { + content = Buffer.from(content, "utf8"); + } + + source.existsAt = targetPath; + source.emitted = true; + this.outputFileSystem.writeFile(targetPath, content, callback); + }; + + if (targetFile.match(/\/|\\/)) { + const dir = path.dirname(targetFile); + this.outputFileSystem.mkdirp( + this.outputFileSystem.join(outputPath, dir), + writeOut + ); + } else { + writeOut(); + } + }, + err => { + if (err) return callback(err); + + this.hooks.afterEmit.callAsync(compilation, err => { + if (err) return callback(err); + + return callback(); + }); + } + ); + }; + + this.hooks.emit.callAsync(compilation, err => { + if (err) return callback(err); + outputPath = compilation.getPath(this.outputPath); + this.outputFileSystem.mkdirp(outputPath, emitFiles); + }); + } + + emitRecords(callback) { + if (!this.recordsOutputPath) return callback(); + const idx1 = this.recordsOutputPath.lastIndexOf("/"); + const idx2 = this.recordsOutputPath.lastIndexOf("\\"); + let recordsOutputPathDirectory = null; + if (idx1 > idx2) { + recordsOutputPathDirectory = this.recordsOutputPath.substr(0, idx1); + } else if (idx1 < idx2) { + recordsOutputPathDirectory = this.recordsOutputPath.substr(0, idx2); + } + + const writeFile = () => { + this.outputFileSystem.writeFile( + this.recordsOutputPath, + JSON.stringify(this.records, undefined, 2), + callback + ); + }; + + if (!recordsOutputPathDirectory) { + return writeFile(); + } + this.outputFileSystem.mkdirp(recordsOutputPathDirectory, err => { + if (err) return callback(err); + writeFile(); + }); + } + + readRecords(callback) { + if (!this.recordsInputPath) { + this.records = {}; + return callback(); + } + this.inputFileSystem.stat(this.recordsInputPath, err => { + // It doesn't exist + // We can ignore this. + if (err) return callback(); + + this.inputFileSystem.readFile(this.recordsInputPath, (err, content) => { + if (err) return callback(err); + + try { + this.records = parseJson(content.toString("utf-8")); + } catch (e) { + e.message = "Cannot parse records: " + e.message; + return callback(e); + } + + return callback(); + }); + }); + } + + createChildCompiler( + compilation, + compilerName, + compilerIndex, + outputOptions, + plugins + ) { + const childCompiler = new Compiler(this.context); + if (Array.isArray(plugins)) { + for (const plugin of plugins) { + plugin.apply(childCompiler); + } + } + for (const name in this.hooks) { + if ( + ![ + "make", + "compile", + "emit", + "afterEmit", + "invalid", + "done", + "thisCompilation" + ].includes(name) + ) { + if (childCompiler.hooks[name]) { + childCompiler.hooks[name].taps = this.hooks[name].taps.slice(); + } + } + } + childCompiler.name = compilerName; + childCompiler.outputPath = this.outputPath; + childCompiler.inputFileSystem = this.inputFileSystem; + childCompiler.outputFileSystem = null; + childCompiler.resolverFactory = this.resolverFactory; + childCompiler.fileTimestamps = this.fileTimestamps; + childCompiler.contextTimestamps = this.contextTimestamps; + + const relativeCompilerName = makePathsRelative(this.context, compilerName); + if (!this.records[relativeCompilerName]) { + this.records[relativeCompilerName] = []; + } + if (this.records[relativeCompilerName][compilerIndex]) { + childCompiler.records = this.records[relativeCompilerName][compilerIndex]; + } else { + this.records[relativeCompilerName].push((childCompiler.records = {})); + } + + childCompiler.options = Object.create(this.options); + childCompiler.options.output = Object.create(childCompiler.options.output); + for (const name in outputOptions) { + childCompiler.options.output[name] = outputOptions[name]; + } + childCompiler.parentCompilation = compilation; + + compilation.hooks.childCompiler.call( + childCompiler, + compilerName, + compilerIndex + ); + + return childCompiler; + } + + isChild() { + return !!this.parentCompilation; + } + + createCompilation() { + return new Compilation(this); + } + + newCompilation(params) { + const compilation = this.createCompilation(); + compilation.fileTimestamps = this.fileTimestamps; + compilation.contextTimestamps = this.contextTimestamps; + compilation.name = this.name; + compilation.records = this.records; + compilation.compilationDependencies = params.compilationDependencies; + this.hooks.thisCompilation.call(compilation, params); + this.hooks.compilation.call(compilation, params); + return compilation; + } + + createNormalModuleFactory() { + const normalModuleFactory = new NormalModuleFactory( + this.options.context, + this.resolverFactory, + this.options.module || {} + ); + this.hooks.normalModuleFactory.call(normalModuleFactory); + return normalModuleFactory; + } + + createContextModuleFactory() { + const contextModuleFactory = new ContextModuleFactory(this.resolverFactory); + this.hooks.contextModuleFactory.call(contextModuleFactory); + return contextModuleFactory; + } + + newCompilationParams() { + const params = { + normalModuleFactory: this.createNormalModuleFactory(), + contextModuleFactory: this.createContextModuleFactory(), + compilationDependencies: new Set() + }; + return params; + } + + compile(callback) { + const params = this.newCompilationParams(); + this.hooks.beforeCompile.callAsync(params, err => { + if (err) return callback(err); + + this.hooks.compile.call(params); + + const compilation = this.newCompilation(params); + + this.hooks.make.callAsync(compilation, err => { + if (err) return callback(err); + + compilation.finish(); + + compilation.seal(err => { + if (err) return callback(err); + + this.hooks.afterCompile.callAsync(compilation, err => { + if (err) return callback(err); + + return callback(null, compilation); + }); + }); + }); + }); + } +} + +module.exports = Compiler; diff --git a/node_modules/webpack/lib/ConstPlugin.js b/node_modules/webpack/lib/ConstPlugin.js index 8534a6fe8..03b279b64 100644 --- a/node_modules/webpack/lib/ConstPlugin.js +++ b/node_modules/webpack/lib/ConstPlugin.js @@ -1,60 +1,258 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const ConstDependency = require("./dependencies/ConstDependency");
-const NullFactory = require("./NullFactory");
-const ParserHelpers = require("./ParserHelpers");
-
-const getQuery = (request) => {
- const i = request.indexOf("?");
- return request.indexOf("?") < 0 ? "" : request.substr(i);
-};
-
-class ConstPlugin {
- apply(compiler) {
- compiler.plugin("compilation", (compilation, params) => {
- compilation.dependencyFactories.set(ConstDependency, new NullFactory());
- compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
-
- params.normalModuleFactory.plugin("parser", parser => {
- parser.plugin("statement if", function(statement) {
- const param = this.evaluateExpression(statement.test);
- const bool = param.asBool();
- if(typeof bool === "boolean") {
- if(statement.test.type !== "Literal") {
- const dep = new ConstDependency(`${bool}`, param.range);
- dep.loc = statement.loc;
- this.state.current.addDependency(dep);
- }
- return bool;
- }
- });
- parser.plugin("expression ?:", function(expression) {
- const param = this.evaluateExpression(expression.test);
- const bool = param.asBool();
- if(typeof bool === "boolean") {
- if(expression.test.type !== "Literal") {
- const dep = new ConstDependency(` ${bool}`, param.range);
- dep.loc = expression.loc;
- this.state.current.addDependency(dep);
- }
- return bool;
- }
- });
- parser.plugin("evaluate Identifier __resourceQuery", function(expr) {
- if(!this.state.module) return;
- return ParserHelpers.evaluateToString(getQuery(this.state.module.resource))(expr);
- });
- parser.plugin("expression __resourceQuery", function() {
- if(!this.state.module) return;
- this.state.current.addVariable("__resourceQuery", JSON.stringify(getQuery(this.state.module.resource)));
- return true;
- });
- });
- });
- }
-}
-
-module.exports = ConstPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const ConstDependency = require("./dependencies/ConstDependency"); +const NullFactory = require("./NullFactory"); +const ParserHelpers = require("./ParserHelpers"); + +const getQuery = request => { + const i = request.indexOf("?"); + return i !== -1 ? request.substr(i) : ""; +}; + +const collectDeclaration = (declarations, pattern) => { + const stack = [pattern]; + while (stack.length > 0) { + const node = 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(property.value); + } + break; + case "RestElement": + stack.push(node.argument); + break; + } + } +}; + +const getHoistedDeclarations = (branch, includeFunctionDeclarations) => { + const declarations = new Set(); + 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, node.id); + } + break; + case "VariableDeclaration": + if (node.kind === "var") { + for (const decl of node.declarations) { + collectDeclaration(declarations, decl.id); + } + } + break; + } + } + return Array.from(declarations); +}; + +class ConstPlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "ConstPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set(ConstDependency, new NullFactory()); + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); + + const handler = parser => { + parser.hooks.statementIf.tap("ConstPlugin", statement => { + const param = parser.evaluateExpression(statement.test); + const bool = param.asBool(); + if (typeof bool === "boolean") { + if (statement.test.type !== "Literal") { + const dep = new ConstDependency(`${bool}`, param.range); + dep.loc = statement.loc; + parser.state.current.addDependency(dep); + } + 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. + // + let declarations; + if (parser.scope.isStrict) { + // If the code runs in strict mode, variable declarations + // using `var` must be hoisted. + declarations = getHoistedDeclarations(branchToRemove, false); + } else { + // Otherwise, collect all hoisted declaration. + declarations = getHoistedDeclarations(branchToRemove, true); + } + let replacement; + if (declarations.length > 0) { + replacement = `{ var ${declarations.join(", ")}; }`; + } else { + replacement = "{}"; + } + const dep = new ConstDependency( + replacement, + branchToRemove.range + ); + dep.loc = branchToRemove.loc; + parser.state.current.addDependency(dep); + } + return bool; + } + }); + parser.hooks.expressionConditionalOperator.tap( + "ConstPlugin", + expression => { + const param = parser.evaluateExpression(expression.test); + const bool = param.asBool(); + if (typeof bool === "boolean") { + if (expression.test.type !== "Literal") { + const dep = new ConstDependency(` ${bool}`, param.range); + dep.loc = expression.loc; + parser.state.current.addDependency(dep); + } + // Expressions do not hoist. + // It is safe to remove the dead branch. + // + // Given the following code: + // + // false ? someExpression() : otherExpression(); + // + // the generated code is: + // + // false ? undefined : otherExpression(); + // + const branchToRemove = bool + ? expression.alternate + : expression.consequent; + const dep = new ConstDependency( + "undefined", + branchToRemove.range + ); + dep.loc = branchToRemove.loc; + parser.state.current.addDependency(dep); + return bool; + } + } + ); + parser.hooks.evaluateIdentifier + .for("__resourceQuery") + .tap("ConstPlugin", expr => { + if (!parser.state.module) return; + return ParserHelpers.evaluateToString( + getQuery(parser.state.module.resource) + )(expr); + }); + parser.hooks.expression + .for("__resourceQuery") + .tap("ConstPlugin", () => { + if (!parser.state.module) return; + parser.state.current.addVariable( + "__resourceQuery", + JSON.stringify(getQuery(parser.state.module.resource)) + ); + return true; + }); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("ConstPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("ConstPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("ConstPlugin", handler); + } + ); + } +} + +module.exports = ConstPlugin; diff --git a/node_modules/webpack/lib/ContextExclusionPlugin.js b/node_modules/webpack/lib/ContextExclusionPlugin.js index db6c81b27..0b1dda0e9 100644 --- a/node_modules/webpack/lib/ContextExclusionPlugin.js +++ b/node_modules/webpack/lib/ContextExclusionPlugin.js @@ -1,17 +1,28 @@ -"use strict";
-
-class ContextExclusionPlugin {
- constructor(negativeMatcher) {
- this.negativeMatcher = negativeMatcher;
- }
-
- apply(compiler) {
- compiler.plugin("context-module-factory", (cmf) => {
- cmf.plugin("context-module-files", (files) => {
- return files.filter(filePath => !this.negativeMatcher.test(filePath));
- });
- });
- }
-}
-
-module.exports = ContextExclusionPlugin;
+"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 Webpack Compiler + * @returns {void} + */ + apply(compiler) { + compiler.hooks.contextModuleFactory.tap("ContextExclusionPlugin", cmf => { + cmf.hooks.contextModuleFiles.tap("ContextExclusionPlugin", files => { + return files.filter(filePath => !this.negativeMatcher.test(filePath)); + }); + }); + } +} + +module.exports = ContextExclusionPlugin; diff --git a/node_modules/webpack/lib/ContextModule.js b/node_modules/webpack/lib/ContextModule.js index a894e6268..78e0e47aa 100644 --- a/node_modules/webpack/lib/ContextModule.js +++ b/node_modules/webpack/lib/ContextModule.js @@ -1,431 +1,844 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const path = require("path");
-const Module = require("./Module");
-const OriginalSource = require("webpack-sources").OriginalSource;
-const RawSource = require("webpack-sources").RawSource;
-const AsyncDependenciesBlock = require("./AsyncDependenciesBlock");
-const DepBlockHelpers = require("./dependencies/DepBlockHelpers");
-const Template = require("./Template");
-
-class ContextModule extends Module {
- constructor(resolveDependencies, context, recursive, regExp, addon, asyncMode, chunkName) {
- super();
- this.resolveDependencies = resolveDependencies;
- this.context = context;
- this.recursive = recursive;
- this.regExp = regExp;
- this.addon = addon;
- this.async = asyncMode;
- this.cacheable = true;
- this.contextDependencies = [context];
- this.built = false;
- this.chunkName = chunkName;
- }
-
- prettyRegExp(regexString) {
- // remove the "/" at the front and the beginning
- // "/foo/" -> "foo"
- return regexString.substring(1, regexString.length - 1);
- }
-
- contextify(context, request) {
- return request.split("!").map(subrequest => {
- let rp = path.relative(context, subrequest);
- if(path.sep === "\\")
- rp = rp.replace(/\\/g, "/");
- if(rp.indexOf("../") !== 0)
- rp = "./" + rp;
- return rp;
- }).join("!");
- }
-
- identifier() {
- let identifier = this.context;
- if(this.async)
- identifier += ` ${this.async}`;
- if(!this.recursive)
- identifier += " nonrecursive";
- if(this.addon)
- identifier += ` ${this.addon}`;
- if(this.regExp)
- identifier += ` ${this.regExp}`;
-
- return identifier;
- }
-
- readableIdentifier(requestShortener) {
- let identifier = requestShortener.shorten(this.context);
- if(this.async)
- identifier += ` ${this.async}`;
- if(!this.recursive)
- identifier += " nonrecursive";
- if(this.addon)
- identifier += ` ${requestShortener.shorten(this.addon)}`;
- if(this.regExp)
- identifier += ` ${this.prettyRegExp(this.regExp + "")}`;
-
- return identifier;
- }
-
- libIdent(options) {
- let identifier = this.contextify(options.context, this.context);
- if(this.async)
- identifier += ` ${this.async}`;
- if(this.recursive)
- identifier += " recursive";
- if(this.addon)
- identifier += ` ${this.contextify(options.context, this.addon)}`;
- if(this.regExp)
- identifier += ` ${this.prettyRegExp(this.regExp + "")}`;
-
- return identifier;
- }
-
- needRebuild(fileTimestamps, contextTimestamps) {
- const ts = contextTimestamps[this.context];
- if(!ts) {
- return true;
- }
-
- return ts >= this.builtTime;
- }
-
- unbuild() {
- this.built = false;
- super.unbuild();
- }
-
- build(options, compilation, resolver, fs, callback) {
- this.built = true;
- this.builtTime = Date.now();
- this.resolveDependencies(fs, this.context, this.recursive, this.regExp, (err, dependencies) => {
- if(err) return callback(err);
-
- // Reset children
- this.dependencies = [];
- this.blocks = [];
-
- // abort if something failed
- // this will create an empty context
- if(!dependencies) {
- callback();
- return;
- }
-
- // enhance dependencies with meta info
- dependencies.forEach(dep => {
- dep.loc = dep.userRequest;
- dep.request = this.addon + dep.request;
- });
-
- if(!this.async || this.async === "eager") {
-
- // if we have an sync or eager context
- // just add all dependencies and continue
- this.dependencies = dependencies;
-
- } else if(this.async === "lazy-once") {
-
- // for the lazy-once mode create a new async dependency block
- // and add that block to this context
- if(dependencies.length > 0) {
- const block = new AsyncDependenciesBlock(this.chunkName, this);
- dependencies.forEach(dep => {
- block.addDependency(dep);
- });
- this.addBlock(block);
- }
-
- } else if(this.async === "weak" || this.async === "async-weak") {
-
- // we mark all dependencies as weak
- dependencies.forEach(dep => dep.weak = true);
- this.dependencies = dependencies;
-
- } else {
- // if we are lazy create a new async dependency block per dependency
- // and add all blocks to this context
- dependencies.forEach((dep, idx) => {
- let chunkName = this.chunkName;
- if(chunkName) {
- if(!/\[(index|request)\]/.test(chunkName))
- chunkName += "[index]";
- chunkName = chunkName.replace(/\[index\]/g, idx);
- chunkName = chunkName.replace(/\[request\]/g, Template.toPath(dep.userRequest));
- }
- const block = new AsyncDependenciesBlock(chunkName, dep.module, dep.loc);
- block.addDependency(dep);
- this.addBlock(block);
- });
- }
- callback();
- });
- }
-
- getUserRequestMap(dependencies) {
- // if we filter first we get a new array
- // therefor we dont need to create a clone of dependencies explicitly
- // therefore the order of this is !important!
- return dependencies
- .filter(dependency => dependency.module)
- .sort((a, b) => {
- if(a.userRequest === b.userRequest) {
- return 0;
- }
- return a.userRequest < b.userRequest ? -1 : 1;
- }).reduce(function(map, dep) {
- map[dep.userRequest] = dep.module.id;
- return map;
- }, Object.create(null));
- }
-
- getSyncSource(dependencies, id) {
- const map = this.getUserRequestMap(dependencies);
- return `var map = ${JSON.stringify(map, null, "\t")};
-function webpackContext(req) {
- return __webpack_require__(webpackContextResolve(req));
-};
-function webpackContextResolve(req) {
- var id = map[req];
- if(!(id + 1)) // check for number or string
- throw new Error("Cannot find module '" + req + "'.");
- return id;
-};
-webpackContext.keys = function webpackContextKeys() {
- return Object.keys(map);
-};
-webpackContext.resolve = webpackContextResolve;
-module.exports = webpackContext;
-webpackContext.id = ${JSON.stringify(id)};`;
- }
-
- getWeakSyncSource(dependencies, id) {
- const map = this.getUserRequestMap(dependencies);
- return `var map = ${JSON.stringify(map, null, "\t")};
-function webpackContext(req) {
- var id = webpackContextResolve(req);
- if(!__webpack_require__.m[id])
- throw new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)");
- return __webpack_require__(id);
-};
-function webpackContextResolve(req) {
- var id = map[req];
- if(!(id + 1)) // check for number or string
- throw new Error("Cannot find module '" + req + "'.");
- return id;
-};
-webpackContext.keys = function webpackContextKeys() {
- return Object.keys(map);
-};
-webpackContext.resolve = webpackContextResolve;
-webpackContext.id = ${JSON.stringify(id)};
-module.exports = webpackContext;`;
- }
-
- getAsyncWeakSource(dependencies, id) {
- const map = this.getUserRequestMap(dependencies);
-
- return `var map = ${JSON.stringify(map, null, "\t")};
-function webpackAsyncContext(req) {
- return webpackAsyncContextResolve(req).then(function(id) {
- if(!__webpack_require__.m[id])
- throw new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)");
- return __webpack_require__(id);
- });
-};
-function webpackAsyncContextResolve(req) {
- // Here Promise.resolve().then() is used instead of new Promise() to prevent
- // uncatched exception popping up in devtools
- return Promise.resolve().then(function() {
- var id = map[req];
- if(!(id + 1)) // check for number or string
- throw new Error("Cannot find module '" + req + "'.");
- return id;
- });
-};
-webpackAsyncContext.keys = function webpackAsyncContextKeys() {
- return Object.keys(map);
-};
-webpackAsyncContext.resolve = webpackAsyncContextResolve;
-webpackAsyncContext.id = ${JSON.stringify(id)};
-module.exports = webpackAsyncContext;`;
- }
-
- getEagerSource(dependencies, id) {
- const map = this.getUserRequestMap(dependencies);
- return `var map = ${JSON.stringify(map, null, "\t")};
-function webpackAsyncContext(req) {
- return webpackAsyncContextResolve(req).then(__webpack_require__);
-};
-function webpackAsyncContextResolve(req) {
- // Here Promise.resolve().then() is used instead of new Promise() to prevent
- // uncatched exception popping up in devtools
- return Promise.resolve().then(function() {
- var id = map[req];
- if(!(id + 1)) // check for number or string
- throw new Error("Cannot find module '" + req + "'.");
- return id;
- });
-};
-webpackAsyncContext.keys = function webpackAsyncContextKeys() {
- return Object.keys(map);
-};
-webpackAsyncContext.resolve = webpackAsyncContextResolve;
-webpackAsyncContext.id = ${JSON.stringify(id)};
-module.exports = webpackAsyncContext;`;
- }
-
- getLazyOnceSource(block, dependencies, id, outputOptions, requestShortener) {
- const promise = DepBlockHelpers.getDepBlockPromise(block, outputOptions, requestShortener, "lazy-once context");
- const map = this.getUserRequestMap(dependencies);
- return `var map = ${JSON.stringify(map, null, "\t")};
-function webpackAsyncContext(req) {
- return webpackAsyncContextResolve(req).then(__webpack_require__);
-};
-function webpackAsyncContextResolve(req) {
- return ${promise}.then(function() {
- var id = map[req];
- if(!(id + 1)) // check for number or string
- throw new Error("Cannot find module '" + req + "'.");
- return id;
- });
-};
-webpackAsyncContext.keys = function webpackAsyncContextKeys() {
- return Object.keys(map);
-};
-webpackAsyncContext.resolve = webpackAsyncContextResolve;
-webpackAsyncContext.id = ${JSON.stringify(id)};
-module.exports = webpackAsyncContext;`;
- }
-
- getLazySource(blocks, id) {
- let hasMultipleOrNoChunks = false;
- const map = blocks
- .filter(block => block.dependencies[0].module)
- .map((block) => ({
- dependency: block.dependencies[0],
- block: block,
- userRequest: block.dependencies[0].userRequest
- })).sort((a, b) => {
- if(a.userRequest === b.userRequest) return 0;
- return a.userRequest < b.userRequest ? -1 : 1;
- }).reduce((map, item) => {
- const chunks = item.block.chunks || [];
- if(chunks.length !== 1) {
- hasMultipleOrNoChunks = true;
- }
- map[item.userRequest] = [item.dependency.module.id]
- .concat(chunks.map(chunk => chunk.id));
-
- return map;
- }, Object.create(null));
-
- const requestPrefix = hasMultipleOrNoChunks ?
- "Promise.all(ids.slice(1).map(__webpack_require__.e))" :
- "__webpack_require__.e(ids[1])";
-
- return `var map = ${JSON.stringify(map, null, "\t")};
-function webpackAsyncContext(req) {
- var ids = map[req];
- if(!ids)
- return Promise.reject(new Error("Cannot find module '" + req + "'."));
- return ${requestPrefix}.then(function() {
- return __webpack_require__(ids[0]);
- });
-};
-webpackAsyncContext.keys = function webpackAsyncContextKeys() {
- return Object.keys(map);
-};
-webpackAsyncContext.id = ${JSON.stringify(id)};
-module.exports = webpackAsyncContext;`;
- }
-
- getSourceForEmptyContext(id) {
- return `function webpackEmptyContext(req) {
- throw new Error("Cannot find module '" + req + "'.");
-}
-webpackEmptyContext.keys = function() { return []; };
-webpackEmptyContext.resolve = webpackEmptyContext;
-module.exports = webpackEmptyContext;
-webpackEmptyContext.id = ${JSON.stringify(id)};`;
- }
-
- getSourceForEmptyAsyncContext(id) {
- return `function webpackEmptyAsyncContext(req) {
- // Here Promise.resolve().then() is used instead of new Promise() to prevent
- // uncatched exception popping up in devtools
- return Promise.resolve().then(function() {
- throw new Error("Cannot find module '" + req + "'.");
- });
-}
-webpackEmptyAsyncContext.keys = function() { return []; };
-webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext;
-module.exports = webpackEmptyAsyncContext;
-webpackEmptyAsyncContext.id = ${JSON.stringify(id)};`;
- }
-
- getSourceString(asyncMode, outputOptions, requestShortener) {
- if(asyncMode === "lazy") {
- if(this.blocks && this.blocks.length > 0) {
- return this.getLazySource(this.blocks, this.id);
- }
- return this.getSourceForEmptyAsyncContext(this.id);
- }
- if(asyncMode === "eager") {
- if(this.dependencies && this.dependencies.length > 0) {
- return this.getEagerSource(this.dependencies, this.id);
- }
- return this.getSourceForEmptyAsyncContext(this.id);
- }
- if(asyncMode === "lazy-once") {
- const block = this.blocks[0];
- if(block) {
- return this.getLazyOnceSource(block, block.dependencies, this.id, outputOptions, requestShortener);
- }
- return this.getSourceForEmptyAsyncContext(this.id);
- }
- if(asyncMode === "async-weak") {
- if(this.dependencies && this.dependencies.length > 0) {
- return this.getAsyncWeakSource(this.dependencies, this.id);
- }
- return this.getSourceForEmptyAsyncContext(this.id);
- }
- if(asyncMode === "weak") {
- if(this.dependencies && this.dependencies.length > 0) {
- return this.getWeakSyncSource(this.dependencies, this.id);
- }
- }
- if(this.dependencies && this.dependencies.length > 0) {
- return this.getSyncSource(this.dependencies, this.id);
- }
- return this.getSourceForEmptyContext(this.id);
- }
-
- getSource(sourceString) {
- if(this.useSourceMap) {
- return new OriginalSource(sourceString, this.identifier());
- }
- return new RawSource(sourceString);
- }
-
- source(dependencyTemplates, outputOptions, requestShortener) {
- return this.getSource(
- this.getSourceString(this.async, outputOptions, requestShortener)
- );
- }
-
- size() {
- // base penalty
- const initialSize = 160;
-
- // if we dont have dependencies we stop here.
- return this.dependencies
- .reduce((size, dependency) => size + 5 + dependency.userRequest.length, initialSize);
- }
-}
-
-module.exports = ContextModule;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const util = require("util"); +const { OriginalSource, RawSource } = require("webpack-sources"); +const Module = require("./Module"); +const AsyncDependenciesBlock = require("./AsyncDependenciesBlock"); +const Template = require("./Template"); +const contextify = require("./util/identifier").contextify; + +/** @typedef {"sync" | "eager" | "weak" | "async-weak" | "lazy" | "lazy-once"} ContextMode Context mode */ +/** @typedef {import("./dependencies/ContextElementDependency")} ContextElementDependency */ + +/** + * @callback ResolveDependenciesCallback + * @param {Error=} err + * @param {ContextElementDependency[]} dependencies + */ + +/** + * @callback ResolveDependencies + * @param {TODO} fs + * @param {TODO} options + * @param {ResolveDependenciesCallback} callback + */ + +class ContextModule extends Module { + // type ContextMode = "sync" | "eager" | "weak" | "async-weak" | "lazy" | "lazy-once" + // type ContextOptions = { resource: string, recursive: boolean, regExp: RegExp, addon?: string, mode?: ContextMode, chunkName?: string, include?: RegExp, exclude?: RegExp, groupOptions?: Object } + // resolveDependencies: (fs: FS, options: ContextOptions, (err: Error?, dependencies: Dependency[]) => void) => void + // options: ContextOptions + /** + * @param {ResolveDependencies} resolveDependencies function to get dependencies in this context + * @param {TODO} options options object + */ + constructor(resolveDependencies, options) { + let resource; + let resourceQuery; + const queryIdx = options.resource.indexOf("?"); + if (queryIdx >= 0) { + resource = options.resource.substr(0, queryIdx); + resourceQuery = options.resource.substr(queryIdx); + } else { + resource = options.resource; + resourceQuery = ""; + } + + super("javascript/dynamic", resource); + + // Info from Factory + this.resolveDependencies = resolveDependencies; + this.options = Object.assign({}, options, { + resource: resource, + resourceQuery: resourceQuery + }); + if (options.resolveOptions !== undefined) { + this.resolveOptions = options.resolveOptions; + } + + // Info from Build + this._contextDependencies = new Set([this.context]); + + if (typeof options.mode !== "string") { + throw new Error("options.mode is a required option"); + } + + this._identifier = this._createIdentifier(); + } + + updateCacheModule(module) { + this.resolveDependencies = module.resolveDependencies; + this.options = module.options; + this.resolveOptions = module.resolveOptions; + } + + prettyRegExp(regexString) { + // remove the "/" at the front and the beginning + // "/foo/" -> "foo" + return regexString.substring(1, regexString.length - 1); + } + + _createIdentifier() { + let identifier = this.context; + if (this.options.resourceQuery) { + identifier += ` ${this.options.resourceQuery}`; + } + if (this.options.mode) { + identifier += ` ${this.options.mode}`; + } + if (!this.options.recursive) { + identifier += " nonrecursive"; + } + if (this.options.addon) { + identifier += ` ${this.options.addon}`; + } + if (this.options.regExp) { + identifier += ` ${this.options.regExp}`; + } + if (this.options.include) { + identifier += ` include: ${this.options.include}`; + } + if (this.options.exclude) { + identifier += ` exclude: ${this.options.exclude}`; + } + if (this.options.groupOptions) { + identifier += ` groupOptions: ${JSON.stringify( + this.options.groupOptions + )}`; + } + if (this.options.namespaceObject === "strict") { + identifier += " strict namespace object"; + } else if (this.options.namespaceObject) { + identifier += " namespace object"; + } + + return identifier; + } + + identifier() { + return this._identifier; + } + + readableIdentifier(requestShortener) { + let identifier = requestShortener.shorten(this.context); + if (this.options.resourceQuery) { + identifier += ` ${this.options.resourceQuery}`; + } + if (this.options.mode) { + identifier += ` ${this.options.mode}`; + } + if (!this.options.recursive) { + identifier += " nonrecursive"; + } + if (this.options.addon) { + identifier += ` ${requestShortener.shorten(this.options.addon)}`; + } + if (this.options.regExp) { + identifier += ` ${this.prettyRegExp(this.options.regExp + "")}`; + } + if (this.options.include) { + identifier += ` include: ${this.prettyRegExp(this.options.include + "")}`; + } + if (this.options.exclude) { + identifier += ` exclude: ${this.prettyRegExp(this.options.exclude + "")}`; + } + if (this.options.groupOptions) { + const groupOptions = this.options.groupOptions; + for (const key of Object.keys(groupOptions)) { + identifier += ` ${key}: ${groupOptions[key]}`; + } + } + if (this.options.namespaceObject === "strict") { + identifier += " strict namespace object"; + } else if (this.options.namespaceObject) { + identifier += " namespace object"; + } + + return identifier; + } + + libIdent(options) { + let identifier = contextify(options.context, this.context); + if (this.options.mode) { + identifier += ` ${this.options.mode}`; + } + if (this.options.recursive) { + identifier += " recursive"; + } + if (this.options.addon) { + identifier += ` ${contextify(options.context, this.options.addon)}`; + } + if (this.options.regExp) { + identifier += ` ${this.prettyRegExp(this.options.regExp + "")}`; + } + if (this.options.include) { + identifier += ` include: ${this.prettyRegExp(this.options.include + "")}`; + } + if (this.options.exclude) { + identifier += ` exclude: ${this.prettyRegExp(this.options.exclude + "")}`; + } + + return identifier; + } + + needRebuild(fileTimestamps, contextTimestamps) { + const ts = contextTimestamps.get(this.context); + if (!ts) { + return true; + } + + return ts >= this.buildInfo.builtTime; + } + + build(options, compilation, resolver, fs, callback) { + this.built = true; + this.buildMeta = {}; + this.buildInfo = { + builtTime: Date.now(), + contextDependencies: this._contextDependencies + }; + this.resolveDependencies(fs, this.options, (err, dependencies) => { + if (err) return callback(err); + + // abort if something failed + // this will create an empty context + if (!dependencies) { + callback(); + return; + } + + // enhance dependencies with meta info + for (const dep of dependencies) { + dep.loc = { + name: dep.userRequest + }; + dep.request = this.options.addon + dep.request; + } + + if (this.options.mode === "sync" || this.options.mode === "eager") { + // if we have an sync or eager context + // just add all dependencies and continue + this.dependencies = dependencies; + } else if (this.options.mode === "lazy-once") { + // for the lazy-once mode create a new async dependency block + // and add that block to this context + if (dependencies.length > 0) { + const block = new AsyncDependenciesBlock( + Object.assign({}, this.options.groupOptions, { + name: this.options.chunkName + }), + this + ); + for (const dep of dependencies) { + block.addDependency(dep); + } + this.addBlock(block); + } + } else if ( + this.options.mode === "weak" || + this.options.mode === "async-weak" + ) { + // we mark all dependencies as weak + for (const dep of dependencies) { + dep.weak = true; + } + this.dependencies = dependencies; + } else if (this.options.mode === "lazy") { + // if we are lazy create a new async dependency block per dependency + // and add all blocks to this context + let index = 0; + for (const dep of dependencies) { + let chunkName = this.options.chunkName; + if (chunkName) { + if (!/\[(index|request)\]/.test(chunkName)) { + chunkName += "[index]"; + } + chunkName = chunkName.replace(/\[index\]/g, index++); + chunkName = chunkName.replace( + /\[request\]/g, + Template.toPath(dep.userRequest) + ); + } + const block = new AsyncDependenciesBlock( + Object.assign({}, this.options.groupOptions, { + name: chunkName + }), + dep.module, + dep.loc, + dep.userRequest + ); + block.addDependency(dep); + this.addBlock(block); + } + } else { + callback( + new Error(`Unsupported mode "${this.options.mode}" in context`) + ); + return; + } + callback(); + }); + } + + getUserRequestMap(dependencies) { + // if we filter first we get a new array + // therefor we dont need to create a clone of dependencies explicitly + // therefore the order of this is !important! + return dependencies + .filter(dependency => dependency.module) + .sort((a, b) => { + if (a.userRequest === b.userRequest) { + return 0; + } + return a.userRequest < b.userRequest ? -1 : 1; + }) + .reduce((map, dep) => { + map[dep.userRequest] = dep.module.id; + return map; + }, Object.create(null)); + } + + getFakeMap(dependencies) { + if (!this.options.namespaceObject) { + return 9; + } + // if we filter first we get a new array + // therefor we dont need to create a clone of dependencies explicitly + // therefore the order of this is !important! + let hasNonHarmony = false; + let hasNamespace = false; + let hasNamed = false; + const fakeMap = dependencies + .filter(dependency => dependency.module) + .sort((a, b) => { + return b.module.id - a.module.id; + }) + .reduce((map, dep) => { + const exportsType = + dep.module.buildMeta && dep.module.buildMeta.exportsType; + const id = dep.module.id; + if (!exportsType) { + map[id] = this.options.namespaceObject === "strict" ? 1 : 7; + hasNonHarmony = true; + } else if (exportsType === "namespace") { + map[id] = 9; + hasNamespace = true; + } else if (exportsType === "named") { + map[id] = 3; + hasNamed = true; + } + return map; + }, Object.create(null)); + if (!hasNamespace && hasNonHarmony && !hasNamed) { + return this.options.namespaceObject === "strict" ? 1 : 7; + } + if (hasNamespace && !hasNonHarmony && !hasNamed) { + return 9; + } + if (!hasNamespace && !hasNonHarmony && hasNamed) { + return 3; + } + if (!hasNamespace && !hasNonHarmony && !hasNamed) { + return 9; + } + return fakeMap; + } + + getFakeMapInitStatement(fakeMap) { + return typeof fakeMap === "object" + ? `var fakeMap = ${JSON.stringify(fakeMap, null, "\t")};` + : ""; + } + + getReturn(type) { + if (type === 9) { + return "__webpack_require__(id)"; + } + return `__webpack_require__.t(id, ${type})`; + } + + getReturnModuleObjectSource(fakeMap, fakeMapDataExpression = "fakeMap[id]") { + if (typeof fakeMap === "number") { + return `return ${this.getReturn(fakeMap)};`; + } + return `return __webpack_require__.t(id, ${fakeMapDataExpression})`; + } + + getSyncSource(dependencies, id) { + const map = this.getUserRequestMap(dependencies); + const fakeMap = this.getFakeMap(dependencies); + const returnModuleObject = this.getReturnModuleObjectSource(fakeMap); + + return `var map = ${JSON.stringify(map, null, "\t")}; +${this.getFakeMapInitStatement(fakeMap)} + +function webpackContext(req) { + var id = webpackContextResolve(req); + ${returnModuleObject} +} +function webpackContextResolve(req) { + var id = map[req]; + if(!(id + 1)) { // check for number or string + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + } + return id; +} +webpackContext.keys = function webpackContextKeys() { + return Object.keys(map); +}; +webpackContext.resolve = webpackContextResolve; +module.exports = webpackContext; +webpackContext.id = ${JSON.stringify(id)};`; + } + + getWeakSyncSource(dependencies, id) { + const map = this.getUserRequestMap(dependencies); + const fakeMap = this.getFakeMap(dependencies); + const returnModuleObject = this.getReturnModuleObjectSource(fakeMap); + + return `var map = ${JSON.stringify(map, null, "\t")}; +${this.getFakeMapInitStatement(fakeMap)} + +function webpackContext(req) { + var id = webpackContextResolve(req); + if(!__webpack_require__.m[id]) { + var e = new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + } + ${returnModuleObject} +} +function webpackContextResolve(req) { + var id = map[req]; + if(!(id + 1)) { // check for number or string + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + } + return id; +} +webpackContext.keys = function webpackContextKeys() { + return Object.keys(map); +}; +webpackContext.resolve = webpackContextResolve; +webpackContext.id = ${JSON.stringify(id)}; +module.exports = webpackContext;`; + } + + getAsyncWeakSource(dependencies, id) { + const map = this.getUserRequestMap(dependencies); + const fakeMap = this.getFakeMap(dependencies); + const returnModuleObject = this.getReturnModuleObjectSource(fakeMap); + + return `var map = ${JSON.stringify(map, null, "\t")}; +${this.getFakeMapInitStatement(fakeMap)} + +function webpackAsyncContext(req) { + return webpackAsyncContextResolve(req).then(function(id) { + if(!__webpack_require__.m[id]) { + var e = new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + } + ${returnModuleObject} + }); +} +function webpackAsyncContextResolve(req) { + // Here Promise.resolve().then() is used instead of new Promise() to prevent + // uncaught exception popping up in devtools + return Promise.resolve().then(function() { + var id = map[req]; + if(!(id + 1)) { // check for number or string + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + } + return id; + }); +} +webpackAsyncContext.keys = function webpackAsyncContextKeys() { + return Object.keys(map); +}; +webpackAsyncContext.resolve = webpackAsyncContextResolve; +webpackAsyncContext.id = ${JSON.stringify(id)}; +module.exports = webpackAsyncContext;`; + } + + getEagerSource(dependencies, id) { + const map = this.getUserRequestMap(dependencies); + const fakeMap = this.getFakeMap(dependencies); + const thenFunction = + fakeMap !== 9 + ? `function(id) { + ${this.getReturnModuleObjectSource(fakeMap)} + }` + : "__webpack_require__"; + return `var map = ${JSON.stringify(map, null, "\t")}; +${this.getFakeMapInitStatement(fakeMap)} + +function webpackAsyncContext(req) { + return webpackAsyncContextResolve(req).then(${thenFunction}); +} +function webpackAsyncContextResolve(req) { + // Here Promise.resolve().then() is used instead of new Promise() to prevent + // uncaught exception popping up in devtools + return Promise.resolve().then(function() { + var id = map[req]; + if(!(id + 1)) { // check for number or string + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + } + return id; + }); +} +webpackAsyncContext.keys = function webpackAsyncContextKeys() { + return Object.keys(map); +}; +webpackAsyncContext.resolve = webpackAsyncContextResolve; +webpackAsyncContext.id = ${JSON.stringify(id)}; +module.exports = webpackAsyncContext;`; + } + + getLazyOnceSource(block, dependencies, id, runtimeTemplate) { + const promise = runtimeTemplate.blockPromise({ + block, + message: "lazy-once context" + }); + const map = this.getUserRequestMap(dependencies); + const fakeMap = this.getFakeMap(dependencies); + const thenFunction = + fakeMap !== 9 + ? `function(id) { + ${this.getReturnModuleObjectSource(fakeMap)}; + }` + : "__webpack_require__"; + + return `var map = ${JSON.stringify(map, null, "\t")}; +${this.getFakeMapInitStatement(fakeMap)} + +function webpackAsyncContext(req) { + return webpackAsyncContextResolve(req).then(${thenFunction}); +} +function webpackAsyncContextResolve(req) { + return ${promise}.then(function() { + var id = map[req]; + if(!(id + 1)) { // check for number or string + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + } + return id; + }); +} +webpackAsyncContext.keys = function webpackAsyncContextKeys() { + return Object.keys(map); +}; +webpackAsyncContext.resolve = webpackAsyncContextResolve; +webpackAsyncContext.id = ${JSON.stringify(id)}; +module.exports = webpackAsyncContext;`; + } + + getLazySource(blocks, id) { + let hasMultipleOrNoChunks = false; + const fakeMap = this.getFakeMap(blocks.map(b => b.dependencies[0])); + const map = blocks + .filter(block => block.dependencies[0].module) + .map(block => ({ + dependency: block.dependencies[0], + block: block, + userRequest: block.dependencies[0].userRequest + })) + .sort((a, b) => { + if (a.userRequest === b.userRequest) return 0; + return a.userRequest < b.userRequest ? -1 : 1; + }) + .reduce((map, item) => { + const chunks = + (item.block.chunkGroup && item.block.chunkGroup.chunks) || []; + if (chunks.length !== 1) { + hasMultipleOrNoChunks = true; + } + const arrayStart = [item.dependency.module.id]; + if (typeof fakeMap === "object") { + arrayStart.push(fakeMap[item.dependency.module.id]); + } + map[item.userRequest] = arrayStart.concat( + chunks.map(chunk => chunk.id) + ); + + return map; + }, Object.create(null)); + + const chunksStartPosition = typeof fakeMap === "object" ? 2 : 1; + const requestPrefix = hasMultipleOrNoChunks + ? `Promise.all(ids.slice(${chunksStartPosition}).map(__webpack_require__.e))` + : `__webpack_require__.e(ids[${chunksStartPosition}])`; + const returnModuleObject = this.getReturnModuleObjectSource( + fakeMap, + "ids[1]" + ); + + return `var map = ${JSON.stringify(map, null, "\t")}; +function webpackAsyncContext(req) { + var ids = map[req]; + if(!ids) { + return Promise.resolve().then(function() { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + }); + } + return ${requestPrefix}.then(function() { + var id = ids[0]; + ${returnModuleObject} + }); +} +webpackAsyncContext.keys = function webpackAsyncContextKeys() { + return Object.keys(map); +}; +webpackAsyncContext.id = ${JSON.stringify(id)}; +module.exports = webpackAsyncContext;`; + } + + getSourceForEmptyContext(id) { + return `function webpackEmptyContext(req) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; +} +webpackEmptyContext.keys = function() { return []; }; +webpackEmptyContext.resolve = webpackEmptyContext; +module.exports = webpackEmptyContext; +webpackEmptyContext.id = ${JSON.stringify(id)};`; + } + + getSourceForEmptyAsyncContext(id) { + return `function webpackEmptyAsyncContext(req) { + // Here Promise.resolve().then() is used instead of new Promise() to prevent + // uncaught exception popping up in devtools + return Promise.resolve().then(function() { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + }); +} +webpackEmptyAsyncContext.keys = function() { return []; }; +webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext; +module.exports = webpackEmptyAsyncContext; +webpackEmptyAsyncContext.id = ${JSON.stringify(id)};`; + } + + getSourceString(asyncMode, runtimeTemplate) { + if (asyncMode === "lazy") { + if (this.blocks && this.blocks.length > 0) { + return this.getLazySource(this.blocks, this.id); + } + return this.getSourceForEmptyAsyncContext(this.id); + } + if (asyncMode === "eager") { + if (this.dependencies && this.dependencies.length > 0) { + return this.getEagerSource(this.dependencies, this.id); + } + return this.getSourceForEmptyAsyncContext(this.id); + } + if (asyncMode === "lazy-once") { + const block = this.blocks[0]; + if (block) { + return this.getLazyOnceSource( + block, + block.dependencies, + this.id, + runtimeTemplate + ); + } + return this.getSourceForEmptyAsyncContext(this.id); + } + if (asyncMode === "async-weak") { + if (this.dependencies && this.dependencies.length > 0) { + return this.getAsyncWeakSource(this.dependencies, this.id); + } + return this.getSourceForEmptyAsyncContext(this.id); + } + if (asyncMode === "weak") { + if (this.dependencies && this.dependencies.length > 0) { + return this.getWeakSyncSource(this.dependencies, this.id); + } + } + if (this.dependencies && this.dependencies.length > 0) { + return this.getSyncSource(this.dependencies, this.id); + } + return this.getSourceForEmptyContext(this.id); + } + + getSource(sourceString) { + if (this.useSourceMap) { + return new OriginalSource(sourceString, this.identifier()); + } + return new RawSource(sourceString); + } + + source(dependencyTemplates, runtimeTemplate) { + return this.getSource( + this.getSourceString(this.options.mode, runtimeTemplate) + ); + } + + size() { + // base penalty + const initialSize = 160; + + // if we dont have dependencies we stop here. + return this.dependencies.reduce((size, dependency) => { + const element = /** @type {ContextElementDependency} */ (dependency); + return size + 5 + element.userRequest.length; + }, initialSize); + } +} + +// TODO remove in webpack 5 +Object.defineProperty(ContextModule.prototype, "recursive", { + configurable: false, + get: util.deprecate( + /** + * @deprecated + * @this {ContextModule} + * @returns {boolean} is recursive + */ + function() { + return this.options.recursive; + }, + "ContextModule.recursive has been moved to ContextModule.options.recursive" + ), + set: util.deprecate( + /** + * @deprecated + * @this {ContextModule} + * @param {boolean} value is recursive + * @returns {void} + */ + function(value) { + this.options.recursive = value; + }, + "ContextModule.recursive has been moved to ContextModule.options.recursive" + ) +}); + +// TODO remove in webpack 5 +Object.defineProperty(ContextModule.prototype, "regExp", { + configurable: false, + get: util.deprecate( + /** + * @deprecated + * @this {ContextModule} + * @returns {RegExp} regular expression + */ + function() { + return this.options.regExp; + }, + "ContextModule.regExp has been moved to ContextModule.options.regExp" + ), + set: util.deprecate( + /** + * @deprecated + * @this {ContextModule} + * @param {RegExp} value Regular expression + * @returns {void} + */ + function(value) { + this.options.regExp = value; + }, + "ContextModule.regExp has been moved to ContextModule.options.regExp" + ) +}); + +// TODO remove in webpack 5 +Object.defineProperty(ContextModule.prototype, "addon", { + configurable: false, + get: util.deprecate( + /** + * @deprecated + * @this {ContextModule} + * @returns {string} addon + */ + function() { + return this.options.addon; + }, + "ContextModule.addon has been moved to ContextModule.options.addon" + ), + set: util.deprecate( + /** + * @deprecated + * @this {ContextModule} + * @param {string} value addon + * @returns {void} + */ + function(value) { + this.options.addon = value; + }, + "ContextModule.addon has been moved to ContextModule.options.addon" + ) +}); + +// TODO remove in webpack 5 +Object.defineProperty(ContextModule.prototype, "async", { + configurable: false, + get: util.deprecate( + /** + * @deprecated + * @this {ContextModule} + * @returns {boolean} is async + */ + function() { + return this.options.mode; + }, + "ContextModule.async has been moved to ContextModule.options.mode" + ), + set: util.deprecate( + /** + * @deprecated + * @this {ContextModule} + * @param {ContextMode} value Context mode + * @returns {void} + */ + function(value) { + this.options.mode = value; + }, + "ContextModule.async has been moved to ContextModule.options.mode" + ) +}); + +// TODO remove in webpack 5 +Object.defineProperty(ContextModule.prototype, "chunkName", { + configurable: false, + get: util.deprecate( + /** + * @deprecated + * @this {ContextModule} + * @returns {string} chunk name + */ + function() { + return this.options.chunkName; + }, + "ContextModule.chunkName has been moved to ContextModule.options.chunkName" + ), + set: util.deprecate( + /** + * @deprecated + * @this {ContextModule} + * @param {string} value chunk name + * @returns {void} + */ + function(value) { + this.options.chunkName = value; + }, + "ContextModule.chunkName has been moved to ContextModule.options.chunkName" + ) +}); + +module.exports = ContextModule; diff --git a/node_modules/webpack/lib/ContextModuleFactory.js b/node_modules/webpack/lib/ContextModuleFactory.js index a3bc34e7e..f59411288 100644 --- a/node_modules/webpack/lib/ContextModuleFactory.js +++ b/node_modules/webpack/lib/ContextModuleFactory.js @@ -1,169 +1,262 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const asyncLib = require("async");
-const path = require("path");
-
-const Tapable = require("tapable");
-const ContextModule = require("./ContextModule");
-const ContextElementDependency = require("./dependencies/ContextElementDependency");
-
-module.exports = class ContextModuleFactory extends Tapable {
- constructor(resolvers) {
- super();
- this.resolvers = resolvers;
- }
-
- create(data, callback) {
- const context = data.context;
- const dependencies = data.dependencies;
- const dependency = dependencies[0];
- this.applyPluginsAsyncWaterfall("before-resolve", {
- context: context,
- request: dependency.request,
- recursive: dependency.recursive,
- regExp: dependency.regExp,
- async: dependency.async,
- dependencies: dependencies
- }, (err, result) => {
- if(err) return callback(err);
-
- // Ignored
- if(!result) return callback();
-
- const context = result.context;
- const request = result.request;
- const recursive = result.recursive;
- const regExp = result.regExp;
- const asyncContext = result.async;
- const dependencies = result.dependencies;
-
- let loaders, resource, loadersPrefix = "";
- const idx = request.lastIndexOf("!");
- if(idx >= 0) {
- loaders = request.substr(0, idx + 1);
- let i;
- for(i = 0; i < loaders.length && loaders[i] === "!"; i++) {
- loadersPrefix += "!";
- }
- loaders = loaders.substr(i).replace(/!+$/, "").replace(/!!+/g, "!");
- if(loaders === "") loaders = [];
- else loaders = loaders.split("!");
- resource = request.substr(idx + 1);
- } else {
- loaders = [];
- resource = request;
- }
-
- const resolvers = this.resolvers;
-
- asyncLib.parallel([
- function(callback) {
- resolvers.context.resolve({}, context, resource, function(err, result) {
- if(err) return callback(err);
- callback(null, result);
- });
- },
- function(callback) {
- asyncLib.map(loaders, function(loader, callback) {
- resolvers.loader.resolve({}, context, loader, function(err, result) {
- if(err) return callback(err);
- callback(null, result);
- });
- }, callback);
- }
- ], (err, result) => {
- if(err) return callback(err);
-
- this.applyPluginsAsyncWaterfall("after-resolve", {
- loaders: loadersPrefix + result[1].join("!") + (result[1].length > 0 ? "!" : ""),
- resource: result[0],
- recursive: recursive,
- regExp: regExp,
- async: asyncContext,
- dependencies: dependencies,
- resolveDependencies: this.resolveDependencies.bind(this)
- }, function(err, result) {
- if(err) return callback(err);
-
- // Ignored
- if(!result) return callback();
-
- return callback(null, new ContextModule(result.resolveDependencies, result.resource, result.recursive, result.regExp, result.loaders, result.async, dependency.chunkName));
- });
- });
- });
- }
-
- resolveDependencies(fs, resource, recursive, regExp, callback) {
- const cmf = this;
- if(!regExp || !resource)
- return callback(null, []);
- (function addDirectory(directory, callback) {
- fs.readdir(directory, (err, files) => {
- if(err) return callback(err);
- files = cmf.applyPluginsWaterfall("context-module-files", files);
- if(!files || files.length === 0) return callback(null, []);
- asyncLib.map(files.filter(function(p) {
- return p.indexOf(".") !== 0;
- }), (seqment, callback) => {
-
- const subResource = path.join(directory, seqment);
-
- 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();
- } else {
- return callback(err);
- }
- }
-
- if(stat.isDirectory()) {
-
- if(!recursive) return callback();
- addDirectory.call(this, subResource, callback);
-
- } else if(stat.isFile()) {
-
- const obj = {
- context: resource,
- request: "." + subResource.substr(resource.length).replace(/\\/g, "/")
- };
-
- this.applyPluginsAsyncWaterfall("alternatives", [obj], (err, alternatives) => {
- if(err) return callback(err);
- alternatives = alternatives.filter(function(obj) {
- return regExp.test(obj.request);
- }).map(function(obj) {
- const dep = new ContextElementDependency(obj.request);
- dep.optional = true;
- return dep;
- });
- callback(null, alternatives);
- });
-
- } else callback();
-
- });
-
- }, (err, result) => {
- if(err) return callback(err);
-
- if(!result) return callback(null, []);
-
- callback(null, result.filter(function(i) {
- return !!i;
- }).reduce(function(a, i) {
- return a.concat(i);
- }, []));
- });
- });
- }.call(this, resource, callback));
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const asyncLib = require("neo-async"); +const path = require("path"); + +const { + Tapable, + AsyncSeriesWaterfallHook, + SyncWaterfallHook +} = require("tapable"); +const ContextModule = require("./ContextModule"); +const ContextElementDependency = require("./dependencies/ContextElementDependency"); + +/** @typedef {import("./Module")} Module */ + +const EMPTY_RESOLVE_OPTIONS = {}; + +module.exports = class ContextModuleFactory extends Tapable { + constructor(resolverFactory) { + super(); + this.hooks = { + /** @type {AsyncSeriesWaterfallHook<TODO>} */ + beforeResolve: new AsyncSeriesWaterfallHook(["data"]), + /** @type {AsyncSeriesWaterfallHook<TODO>} */ + afterResolve: new AsyncSeriesWaterfallHook(["data"]), + /** @type {SyncWaterfallHook<string[]>} */ + contextModuleFiles: new SyncWaterfallHook(["files"]), + /** @type {SyncWaterfallHook<TODO[]>} */ + alternatives: new AsyncSeriesWaterfallHook(["modules"]) + }; + this._pluginCompat.tap("ContextModuleFactory", options => { + switch (options.name) { + case "before-resolve": + case "after-resolve": + case "alternatives": + options.async = true; + break; + } + }); + this.resolverFactory = resolverFactory; + } + + create(data, callback) { + const context = data.context; + const dependencies = data.dependencies; + const resolveOptions = data.resolveOptions; + const dependency = dependencies[0]; + this.hooks.beforeResolve.callAsync( + Object.assign( + { + context: context, + dependencies: dependencies, + resolveOptions + }, + dependency.options + ), + (err, beforeResolveResult) => { + if (err) return callback(err); + + // Ignored + if (!beforeResolveResult) return callback(); + + const context = beforeResolveResult.context; + const request = beforeResolveResult.request; + const resolveOptions = beforeResolveResult.resolveOptions; + + let loaders, + resource, + loadersPrefix = ""; + const idx = request.lastIndexOf("!"); + if (idx >= 0) { + let loadersRequest = request.substr(0, idx + 1); + let i; + for ( + i = 0; + i < loadersRequest.length && loadersRequest[i] === "!"; + i++ + ) { + loadersPrefix += "!"; + } + loadersRequest = loadersRequest + .substr(i) + .replace(/!+$/, "") + .replace(/!!+/g, "!"); + if (loadersRequest === "") { + loaders = []; + } else { + loaders = loadersRequest.split("!"); + } + resource = request.substr(idx + 1); + } else { + loaders = []; + resource = request; + } + + const contextResolver = this.resolverFactory.get( + "context", + resolveOptions || EMPTY_RESOLVE_OPTIONS + ); + const loaderResolver = this.resolverFactory.get( + "loader", + EMPTY_RESOLVE_OPTIONS + ); + + asyncLib.parallel( + [ + callback => { + contextResolver.resolve( + {}, + context, + resource, + {}, + (err, result) => { + if (err) return callback(err); + callback(null, result); + } + ); + }, + callback => { + asyncLib.map( + loaders, + (loader, callback) => { + loaderResolver.resolve( + {}, + context, + loader, + {}, + (err, result) => { + if (err) return callback(err); + callback(null, result); + } + ); + }, + callback + ); + } + ], + (err, result) => { + if (err) return callback(err); + + this.hooks.afterResolve.callAsync( + Object.assign( + { + addon: + loadersPrefix + + result[1].join("!") + + (result[1].length > 0 ? "!" : ""), + resource: result[0], + resolveDependencies: this.resolveDependencies.bind(this) + }, + beforeResolveResult + ), + (err, result) => { + if (err) return callback(err); + + // Ignored + if (!result) return callback(); + + return callback( + null, + new ContextModule(result.resolveDependencies, result) + ); + } + ); + } + ); + } + ); + } + + resolveDependencies(fs, options, callback) { + const cmf = this; + let resource = options.resource; + let resourceQuery = options.resourceQuery; + let recursive = options.recursive; + let regExp = options.regExp; + let include = options.include; + let exclude = options.exclude; + if (!regExp || !resource) return callback(null, []); + + const addDirectory = (directory, callback) => { + fs.readdir(directory, (err, files) => { + if (err) return callback(err); + files = cmf.hooks.contextModuleFiles.call(files); + if (!files || files.length === 0) return callback(null, []); + asyncLib.map( + files.filter(p => p.indexOf(".") !== 0), + (segment, callback) => { + const subResource = path.join(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(); + } else { + return callback(err); + } + } + + if (stat.isDirectory()) { + if (!recursive) return callback(); + addDirectory.call(this, subResource, callback); + } else if ( + stat.isFile() && + (!include || subResource.match(include)) + ) { + const obj = { + context: resource, + request: + "." + + subResource.substr(resource.length).replace(/\\/g, "/") + }; + + this.hooks.alternatives.callAsync( + [obj], + (err, alternatives) => { + if (err) return callback(err); + alternatives = alternatives + .filter(obj => regExp.test(obj.request)) + .map(obj => { + const dep = new ContextElementDependency( + obj.request + resourceQuery, + obj.request + ); + dep.optional = true; + return dep; + }); + callback(null, alternatives); + } + ); + } else { + callback(); + } + }); + } else { + callback(); + } + }, + (err, result) => { + if (err) return callback(err); + + if (!result) return callback(null, []); + + callback( + null, + result.filter(Boolean).reduce((a, i) => a.concat(i), []) + ); + } + ); + }); + }; + + addDirectory(resource, callback); + } +}; diff --git a/node_modules/webpack/lib/ContextReplacementPlugin.js b/node_modules/webpack/lib/ContextReplacementPlugin.js index 29fede826..5523c8ab6 100644 --- a/node_modules/webpack/lib/ContextReplacementPlugin.js +++ b/node_modules/webpack/lib/ContextReplacementPlugin.js @@ -1,111 +1,133 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const path = require("path");
-const ContextElementDependency = require("./dependencies/ContextElementDependency");
-
-class ContextReplacementPlugin {
- 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(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.plugin("context-module-factory", (cmf) => {
- cmf.plugin("before-resolve", (result, callback) => {
- if(!result) return callback();
- if(resourceRegExp.test(result.request)) {
- if(typeof newContentResource !== "undefined")
- result.request = newContentResource;
- if(typeof newContentRecursive !== "undefined")
- result.recursive = newContentRecursive;
- if(typeof newContentRegExp !== "undefined")
- result.regExp = newContentRegExp;
- if(typeof newContentCallback === "function") {
- newContentCallback(result);
- } else {
- result.dependencies.forEach((d) => {
- if(d.critical)
- d.critical = false;
- });
- }
- }
- return callback(null, result);
- });
- cmf.plugin("after-resolve", (result, callback) => {
- if(!result) return callback();
- if(resourceRegExp.test(result.resource)) {
- if(typeof newContentResource !== "undefined")
- result.resource = path.resolve(result.resource, newContentResource);
- if(typeof newContentRecursive !== "undefined")
- result.recursive = newContentRecursive;
- if(typeof 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 = path.resolve(origResource, result.resource);
- }
- } else {
- result.dependencies.forEach((d) => {
- if(d.critical)
- d.critical = false;
- });
- }
- }
- return callback(null, result);
- });
- });
- }
-}
-
-const createResolveDependenciesFromContextMap = (createContextMap) => {
- return function resolveDependenciesFromContextMap(fs, resource, recursive, regExp, callback) {
- createContextMap(fs, (err, map) => {
- if(err) return callback(err);
- const dependencies = Object.keys(map).map((key) => {
- return new ContextElementDependency(map[key], key);
- });
- callback(null, dependencies);
- });
- };
-};
-
-module.exports = ContextReplacementPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const path = require("path"); +const ContextElementDependency = require("./dependencies/ContextElementDependency"); + +class ContextReplacementPlugin { + 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(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) { + result.resource = path.resolve(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 = path.resolve(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 => { + return new ContextElementDependency( + map[key] + options.resourceQuery, + key + ); + }); + callback(null, dependencies); + }); + }; + return resolveDependenciesFromContextMap; +}; + +module.exports = ContextReplacementPlugin; diff --git a/node_modules/webpack/lib/DefinePlugin.js b/node_modules/webpack/lib/DefinePlugin.js index 6318124f5..805b055ef 100644 --- a/node_modules/webpack/lib/DefinePlugin.js +++ b/node_modules/webpack/lib/DefinePlugin.js @@ -1,123 +1,283 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const ConstDependency = require("./dependencies/ConstDependency");
-const BasicEvaluatedExpression = require("./BasicEvaluatedExpression");
-const ParserHelpers = require("./ParserHelpers");
-const NullFactory = require("./NullFactory");
-
-class DefinePlugin {
- constructor(definitions) {
- this.definitions = definitions;
- }
-
- apply(compiler) {
- const definitions = this.definitions;
- compiler.plugin("compilation", (compilation, params) => {
- compilation.dependencyFactories.set(ConstDependency, new NullFactory());
- compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
-
- params.normalModuleFactory.plugin("parser", (parser) => {
- (function walkDefinitions(definitions, prefix) {
- Object.keys(definitions).forEach((key) => {
- const code = definitions[key];
- if(code && typeof code === "object" && !(code instanceof RegExp)) {
- walkDefinitions(code, prefix + key + ".");
- applyObjectDefine(prefix + key, code);
- return;
- }
- applyDefineKey(prefix, key);
- applyDefine(prefix + key, code);
- });
- }(definitions, ""));
-
- function stringifyObj(obj) {
- return "Object({" + Object.keys(obj).map((key) => {
- const code = obj[key];
- return JSON.stringify(key) + ":" + toCode(code);
- }).join(",") + "})";
- }
-
- function toCode(code) {
- if(code === null) return "null";
- else if(code === undefined) return "undefined";
- else if(code instanceof RegExp && code.toString) return code.toString();
- else if(typeof code === "function" && code.toString) return "(" + code.toString() + ")";
- else if(typeof code === "object") return stringifyObj(code);
- else return code + "";
- }
-
- function applyDefineKey(prefix, key) {
- const splittedKey = key.split(".");
- splittedKey.slice(1).forEach((_, i) => {
- const fullKey = prefix + splittedKey.slice(0, i + 1).join(".");
- parser.plugin("can-rename " + fullKey, ParserHelpers.approve);
- });
- }
-
- function applyDefine(key, code) {
- const isTypeof = /^typeof\s+/.test(key);
- if(isTypeof) key = key.replace(/^typeof\s+/, "");
- let recurse = false;
- let recurseTypeof = false;
- code = toCode(code);
- if(!isTypeof) {
- parser.plugin("can-rename " + key, ParserHelpers.approve);
- parser.plugin("evaluate Identifier " + key, (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;
- recurse = true;
- const res = parser.evaluate(code);
- recurse = false;
- res.setRange(expr.range);
- return res;
- });
- parser.plugin("expression " + key, ParserHelpers.toConstantDependency(code));
- }
- const typeofCode = isTypeof ? code : "typeof (" + code + ")";
- parser.plugin("evaluate typeof " + key, (expr) => {
- /**
- * this is needed in case there is a recursion in the DefinePlugin
- * to prevent an endless recursion
- * e.g.: new DefinePlugin({
- * "typeof a": "tyepof b",
- * "typeof b": "typeof a"
- * });
- */
- if(recurseTypeof) return;
- recurseTypeof = true;
- const res = parser.evaluate(typeofCode);
- recurseTypeof = false;
- res.setRange(expr.range);
- return res;
- });
- parser.plugin("typeof " + key, (expr) => {
- const res = parser.evaluate(typeofCode);
- if(!res.isString()) return;
- return ParserHelpers.toConstantDependency(JSON.stringify(res.string)).bind(parser)(expr);
- });
- }
-
- function applyObjectDefine(key, obj) {
- const code = stringifyObj(obj);
- parser.plugin("can-rename " + key, ParserHelpers.approve);
- parser.plugin("evaluate Identifier " + key, (expr) => new BasicEvaluatedExpression().setTruthy().setRange(expr.range));
- parser.plugin("evaluate typeof " + key, ParserHelpers.evaluateToString("object"));
- parser.plugin("expression " + key, ParserHelpers.toConstantDependency(code));
- parser.plugin("typeof " + key, ParserHelpers.toConstantDependency(JSON.stringify("object")));
- }
- });
- });
- }
-}
-module.exports = DefinePlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const ConstDependency = require("./dependencies/ConstDependency"); +const BasicEvaluatedExpression = require("./BasicEvaluatedExpression"); +const ParserHelpers = require("./ParserHelpers"); +const NullFactory = require("./NullFactory"); + +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Parser")} Parser */ +/** @typedef {null|undefined|RegExp|Function|string|number} CodeValuePrimitive */ +/** @typedef {CodeValuePrimitive|Record<string, CodeValuePrimitive>|RuntimeValue} CodeValue */ + +class RuntimeValue { + constructor(fn, fileDependencies) { + this.fn = fn; + this.fileDependencies = fileDependencies || []; + } + + exec(parser) { + for (const fileDependency of this.fileDependencies) { + parser.state.module.buildInfo.fileDependencies.add(fileDependency); + } + + return this.fn(); + } +} + +const stringifyObj = (obj, parser) => { + return ( + "Object({" + + Object.keys(obj) + .map(key => { + const code = obj[key]; + return JSON.stringify(key) + ":" + toCode(code, parser); + }) + .join(",") + + "})" + ); +}; + +/** + * Convert code to a string that evaluates + * @param {CodeValue} code Code to evaluate + * @param {Parser} parser Parser + * @returns {string} code converted to string that evaluates + */ +const toCode = (code, parser) => { + if (code === null) { + return "null"; + } + if (code === undefined) { + return "undefined"; + } + if (code instanceof RuntimeValue) { + return toCode(code.exec(parser), parser); + } + 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); + } + return code + ""; +}; + +class DefinePlugin { + /** + * Create a new define plugin + * @param {Record<string, CodeValue>} definitions A map of global object definitions + */ + constructor(definitions) { + this.definitions = definitions; + } + + static runtimeValue(fn, fileDependencies) { + return new RuntimeValue(fn, fileDependencies); + } + + /** + * Apply the plugin + * @param {Compiler} compiler Webpack compiler + * @returns {void} + */ + apply(compiler) { + const definitions = this.definitions; + compiler.hooks.compilation.tap( + "DefinePlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set(ConstDependency, new NullFactory()); + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); + + /** + * Handler + * @param {Parser} parser Parser + * @returns {void} + */ + const handler = parser => { + /** + * Walk definitions + * @param {Object} definitions Definitions map + * @param {string} prefix Prefix string + * @returns {void} + */ + const walkDefinitions = (definitions, prefix) => { + Object.keys(definitions).forEach(key => { + const code = definitions[key]; + if ( + code && + typeof code === "object" && + !(code instanceof RuntimeValue) && + !(code instanceof RegExp) + ) { + walkDefinitions(code, prefix + key + "."); + applyObjectDefine(prefix + key, code); + return; + } + 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("."); + splittedKey.slice(1).forEach((_, i) => { + const fullKey = prefix + splittedKey.slice(0, i + 1).join("."); + parser.hooks.canRename + .for(fullKey) + .tap("DefinePlugin", ParserHelpers.approve); + }); + }; + + /** + * Apply Code + * @param {string} key Key + * @param {CodeValue} code Code + * @returns {void} + */ + const applyDefine = (key, code) => { + const isTypeof = /^typeof\s+/.test(key); + if (isTypeof) key = key.replace(/^typeof\s+/, ""); + let recurse = false; + let recurseTypeof = false; + if (!isTypeof) { + parser.hooks.canRename + .for(key) + .tap("DefinePlugin", ParserHelpers.approve); + parser.hooks.evaluateIdentifier + .for(key) + .tap("DefinePlugin", 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; + recurse = true; + const res = parser.evaluate(toCode(code, parser)); + recurse = false; + res.setRange(expr.range); + return res; + }); + parser.hooks.expression.for(key).tap("DefinePlugin", expr => { + const strCode = toCode(code, parser); + if (/__webpack_require__/.test(strCode)) { + return ParserHelpers.toConstantDependencyWithWebpackRequire( + parser, + strCode + )(expr); + } else { + return ParserHelpers.toConstantDependency(parser, strCode)( + expr + ); + } + }); + } + parser.hooks.evaluateTypeof.for(key).tap("DefinePlugin", 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; + const typeofCode = isTypeof + ? toCode(code, parser) + : "typeof (" + toCode(code, parser) + ")"; + const res = parser.evaluate(typeofCode); + recurseTypeof = false; + res.setRange(expr.range); + return res; + }); + parser.hooks.typeof.for(key).tap("DefinePlugin", expr => { + const typeofCode = isTypeof + ? toCode(code, parser) + : "typeof (" + toCode(code, parser) + ")"; + const res = parser.evaluate(typeofCode); + if (!res.isString()) return; + return ParserHelpers.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("DefinePlugin", ParserHelpers.approve); + parser.hooks.evaluateIdentifier + .for(key) + .tap("DefinePlugin", expr => + new BasicEvaluatedExpression().setTruthy().setRange(expr.range) + ); + parser.hooks.evaluateTypeof.for(key).tap("DefinePlugin", expr => { + return ParserHelpers.evaluateToString("object")(expr); + }); + parser.hooks.expression.for(key).tap("DefinePlugin", expr => { + const strCode = stringifyObj(obj, parser); + + if (/__webpack_require__/.test(strCode)) { + return ParserHelpers.toConstantDependencyWithWebpackRequire( + parser, + strCode + )(expr); + } else { + return ParserHelpers.toConstantDependency(parser, strCode)( + expr + ); + } + }); + parser.hooks.typeof.for(key).tap("DefinePlugin", expr => { + return ParserHelpers.toConstantDependency( + parser, + JSON.stringify("object") + )(expr); + }); + }; + + walkDefinitions(definitions, ""); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("DefinePlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("DefinePlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("DefinePlugin", handler); + } + ); + } +} +module.exports = DefinePlugin; diff --git a/node_modules/webpack/lib/DelegatedModule.js b/node_modules/webpack/lib/DelegatedModule.js index 4046d03d5..170ceca7a 100644 --- a/node_modules/webpack/lib/DelegatedModule.js +++ b/node_modules/webpack/lib/DelegatedModule.js @@ -1,98 +1,114 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const Module = require("./Module");
-const OriginalSource = require("webpack-sources").OriginalSource;
-const RawSource = require("webpack-sources").RawSource;
-const WebpackMissingModule = require("./dependencies/WebpackMissingModule");
-const DelegatedSourceDependency = require("./dependencies/DelegatedSourceDependency");
-const DelegatedExportsDependency = require("./dependencies/DelegatedExportsDependency");
-
-class DelegatedModule extends Module {
- constructor(sourceRequest, data, type, userRequest, originalRequest) {
- super();
- this.sourceRequest = sourceRequest;
- this.request = data.id;
- this.meta = data.meta;
- this.type = type;
- this.originalRequest = originalRequest;
- this.userRequest = userRequest;
- this.built = false;
- this.delegated = true;
- this.delegateData = data;
- }
-
- libIdent(options) {
- return typeof this.originalRequest === "string" ? this.originalRequest : this.originalRequest.libIdent(options);
- }
-
- identifier() {
- return `delegated ${JSON.stringify(this.request)} from ${this.sourceRequest}`;
- }
-
- readableIdentifier() {
- return `delegated ${this.userRequest} from ${this.sourceRequest}`;
- }
-
- needRebuild() {
- return false;
- }
-
- build(options, compilation, resolver, fs, callback) {
- this.built = true;
- this.builtTime = Date.now();
- this.cacheable = true;
- this.dependencies.length = 0;
- this.addDependency(new DelegatedSourceDependency(this.sourceRequest));
- this.addDependency(new DelegatedExportsDependency(this, this.delegateData.exports || true));
- callback();
- }
-
- unbuild() {
- this.built = false;
- super.unbuild();
- }
-
- source() {
- const sourceModule = this.dependencies[0].module;
- let str;
-
- if(!sourceModule) {
- str = WebpackMissingModule.moduleCode(this.sourceRequest);
- } else {
- str = `module.exports = (__webpack_require__(${JSON.stringify(sourceModule.id)}))`;
-
- switch(this.type) {
- case "require":
- str += `(${JSON.stringify(this.request)})`;
- break;
- case "object":
- str += `[${JSON.stringify(this.request)}]`;
- break;
- }
-
- str += ";";
- }
-
- if(this.useSourceMap) {
- return new OriginalSource(str, this.identifier());
- } else {
- return new RawSource(str);
- }
- }
-
- size() {
- return 42;
- }
-
- updateHash(hash) {
- hash.update(this.type);
- hash.update(JSON.stringify(this.request));
- super.updateHash(hash);
- }
-}
-
-module.exports = DelegatedModule;
+/* + 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 WebpackMissingModule = require("./dependencies/WebpackMissingModule"); +const DelegatedSourceDependency = require("./dependencies/DelegatedSourceDependency"); +const DelegatedExportsDependency = require("./dependencies/DelegatedExportsDependency"); + +/** @typedef {import("./dependencies/ModuleDependency")} ModuleDependency */ +/** @typedef {import("./util/createHash").Hash} Hash */ + +class DelegatedModule extends Module { + constructor(sourceRequest, data, type, userRequest, originalRequest) { + super("javascript/dynamic", null); + + // Info from Factory + this.sourceRequest = sourceRequest; + this.request = data.id; + this.type = type; + this.userRequest = userRequest; + this.originalRequest = originalRequest; + this.delegateData = data; + + // Build info + this.delegatedSourceDependency = undefined; + } + + libIdent(options) { + return typeof this.originalRequest === "string" + ? this.originalRequest + : this.originalRequest.libIdent(options); + } + + identifier() { + return `delegated ${JSON.stringify(this.request)} from ${ + this.sourceRequest + }`; + } + + readableIdentifier() { + return `delegated ${this.userRequest} from ${this.sourceRequest}`; + } + + needRebuild() { + return false; + } + + build(options, compilation, resolver, fs, callback) { + this.built = true; + this.buildMeta = Object.assign({}, this.delegateData.buildMeta); + this.buildInfo = {}; + this.delegatedSourceDependency = new DelegatedSourceDependency( + this.sourceRequest + ); + this.addDependency(this.delegatedSourceDependency); + this.addDependency( + new DelegatedExportsDependency(this, this.delegateData.exports || true) + ); + callback(); + } + + source(depTemplates, runtime) { + const dep = /** @type {DelegatedSourceDependency} */ (this.dependencies[0]); + const sourceModule = dep.module; + let str; + + if (!sourceModule) { + str = WebpackMissingModule.moduleCode(this.sourceRequest); + } else { + str = `module.exports = (${runtime.moduleExports({ + module: sourceModule, + request: dep.request + })})`; + + switch (this.type) { + case "require": + str += `(${JSON.stringify(this.request)})`; + break; + case "object": + str += `[${JSON.stringify(this.request)}]`; + break; + } + + str += ";"; + } + + if (this.useSourceMap) { + return new OriginalSource(str, this.identifier()); + } else { + return new RawSource(str); + } + } + + size() { + return 42; + } + + /** + * @param {Hash} hash the hash used to track dependencies + * @returns {void} + */ + updateHash(hash) { + hash.update(this.type); + hash.update(JSON.stringify(this.request)); + super.updateHash(hash); + } +} + +module.exports = DelegatedModule; diff --git a/node_modules/webpack/lib/DelegatedModuleFactoryPlugin.js b/node_modules/webpack/lib/DelegatedModuleFactoryPlugin.js index f26dfca94..a0a05a438 100644 --- a/node_modules/webpack/lib/DelegatedModuleFactoryPlugin.js +++ b/node_modules/webpack/lib/DelegatedModuleFactoryPlugin.js @@ -1,59 +1,95 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const DelegatedModule = require("./DelegatedModule");
-
-// options.source
-// options.type
-// options.context
-// options.scope
-// options.content
-class DelegatedModuleFactoryPlugin {
- constructor(options) {
- this.options = options;
- options.type = options.type || "require";
- options.extensions = options.extensions || ["", ".js"];
- }
-
- apply(normalModuleFactory) {
- const scope = this.options.scope;
- if(scope) {
- normalModuleFactory.plugin("factory", factory => (data, callback) => {
- const dependency = data.dependencies[0];
- const request = dependency.request;
- if(request && request.indexOf(scope + "/") === 0) {
- const innerRequest = "." + request.substr(scope.length);
- let resolved;
- if(innerRequest in this.options.content) {
- resolved = this.options.content[innerRequest];
- return callback(null, new DelegatedModule(this.options.source, resolved, this.options.type, innerRequest, request));
- }
- for(let i = 0; i < this.options.extensions.length; i++) {
- const extension = this.options.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, this.options.type, requestPlusExt, request + extension));
- }
- }
- }
- return factory(data, callback);
- });
- } else {
- normalModuleFactory.plugin("module", module => {
- if(module.libIdent) {
- 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, this.options.type, request, module);
- }
- }
- return module;
- });
- }
- }
-}
-module.exports = DelegatedModuleFactoryPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const DelegatedModule = require("./DelegatedModule"); + +// options.source +// options.type +// options.context +// options.scope +// options.content +class DelegatedModuleFactoryPlugin { + constructor(options) { + this.options = options; + options.type = options.type || "require"; + options.extensions = options.extensions || [ + "", + ".wasm", + ".mjs", + ".js", + ".json" + ]; + } + + apply(normalModuleFactory) { + const scope = this.options.scope; + if (scope) { + normalModuleFactory.hooks.factory.tap( + "DelegatedModuleFactoryPlugin", + factory => (data, callback) => { + const dependency = data.dependencies[0]; + const request = dependency.request; + if (request && request.indexOf(scope + "/") === 0) { + const innerRequest = "." + request.substr(scope.length); + let resolved; + if (innerRequest in this.options.content) { + resolved = this.options.content[innerRequest]; + return callback( + null, + new DelegatedModule( + this.options.source, + resolved, + this.options.type, + innerRequest, + request + ) + ); + } + for (let i = 0; i < this.options.extensions.length; i++) { + const extension = this.options.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, + this.options.type, + requestPlusExt, + request + extension + ) + ); + } + } + } + return factory(data, callback); + } + ); + } else { + normalModuleFactory.hooks.module.tap( + "DelegatedModuleFactoryPlugin", + module => { + if (module.libIdent) { + 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, + this.options.type, + request, + module + ); + } + } + return module; + } + ); + } + } +} +module.exports = DelegatedModuleFactoryPlugin; diff --git a/node_modules/webpack/lib/DelegatedPlugin.js b/node_modules/webpack/lib/DelegatedPlugin.js index 67894d9bd..714eb8533 100644 --- a/node_modules/webpack/lib/DelegatedPlugin.js +++ b/node_modules/webpack/lib/DelegatedPlugin.js @@ -1,30 +1,39 @@ -/*
- 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");
-const DelegatedExportsDependency = require("./dependencies/DelegatedExportsDependency");
-const NullFactory = require("./NullFactory");
-
-class DelegatedPlugin {
- constructor(options) {
- this.options = options;
- }
-
- apply(compiler) {
- compiler.plugin("compilation", (compilation, params) => {
- compilation.dependencyFactories.set(DelegatedSourceDependency, params.normalModuleFactory);
- compilation.dependencyFactories.set(DelegatedExportsDependency, new NullFactory());
- });
-
- compiler.plugin("compile", (params) => {
- params.normalModuleFactory.apply(new DelegatedModuleFactoryPlugin(this.options));
- });
- }
-}
-
-module.exports = DelegatedPlugin;
+/* + 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"); +const DelegatedExportsDependency = require("./dependencies/DelegatedExportsDependency"); +const NullFactory = require("./NullFactory"); + +class DelegatedPlugin { + constructor(options) { + this.options = options; + } + + apply(compiler) { + compiler.hooks.compilation.tap( + "DelegatedPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + DelegatedSourceDependency, + normalModuleFactory + ); + compilation.dependencyFactories.set( + DelegatedExportsDependency, + new NullFactory() + ); + } + ); + + compiler.hooks.compile.tap("DelegatedPlugin", ({ normalModuleFactory }) => { + new DelegatedModuleFactoryPlugin(this.options).apply(normalModuleFactory); + }); + } +} + +module.exports = DelegatedPlugin; diff --git a/node_modules/webpack/lib/DependenciesBlock.js b/node_modules/webpack/lib/DependenciesBlock.js index d8b07c1db..142f3eacb 100644 --- a/node_modules/webpack/lib/DependenciesBlock.js +++ b/node_modules/webpack/lib/DependenciesBlock.js @@ -1,81 +1,124 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
- */
-"use strict";
-
-const DependenciesBlockVariable = require("./DependenciesBlockVariable");
-
-function disconnect(i) {
- i.disconnect();
-}
-
-function unseal(i) {
- i.unseal();
-}
-
-class DependenciesBlock {
- constructor() {
- this.dependencies = [];
- this.blocks = [];
- this.variables = [];
- }
-
- addBlock(block) {
- this.blocks.push(block);
- block.parent = this;
- }
-
- addVariable(name, expression, dependencies) {
- for(let v of this.variables) {
- if(v.name === name && v.expression === expression) {
- return;
- }
- }
- this.variables.push(new DependenciesBlockVariable(name, expression, dependencies));
- }
-
- addDependency(dependency) {
- this.dependencies.push(dependency);
- }
-
- updateHash(hash) {
- function updateHash(i) {
- i.updateHash(hash);
- }
-
- this.dependencies.forEach(updateHash);
- this.blocks.forEach(updateHash);
- this.variables.forEach(updateHash);
- }
-
- disconnect() {
- this.dependencies.forEach(disconnect);
- this.blocks.forEach(disconnect);
- this.variables.forEach(disconnect);
- }
-
- unseal() {
- this.blocks.forEach(unseal);
- }
-
- hasDependencies(filter) {
- if(filter) {
- if(this.dependencies.some(filter)) {
- return true;
- }
- } else {
- if(this.dependencies.length > 0) {
- return true;
- }
- }
-
- return this.blocks.concat(this.variables).some(item => item.hasDependencies(filter));
- }
-
- sortItems() {
- this.blocks.forEach(block => block.sortItems());
- }
-}
-
-module.exports = DependenciesBlock;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra + */ +"use strict"; + +const DependenciesBlockVariable = require("./DependenciesBlockVariable"); + +/** @typedef {import("./ChunkGroup")} ChunkGroup */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ +/** @typedef {import("./DependenciesBlockVariable")} DependenciesBlockVariable */ +/** @typedef {(d: Dependency) => boolean} DependencyFilterFunction */ +/** @typedef {import("./util/createHash").Hash} Hash */ + +class DependenciesBlock { + constructor() { + /** @type {Dependency[]} */ + this.dependencies = []; + /** @type {AsyncDependenciesBlock[]} */ + this.blocks = []; + /** @type {DependenciesBlockVariable[]} */ + this.variables = []; + } + + /** + * 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 {string} name name of dependency + * @param {string} expression expression string for variable + * @param {Dependency[]} dependencies dependency instances tied to variable + * @returns {void} + */ + addVariable(name, expression, dependencies) { + for (let v of this.variables) { + if (v.name === name && v.expression === expression) { + return; + } + } + this.variables.push( + new DependenciesBlockVariable(name, expression, dependencies) + ); + } + + /** + * @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); + } + } + + /** + * @param {Hash} hash the hash used to track dependencies + * @returns {void} + */ + updateHash(hash) { + for (const dep of this.dependencies) dep.updateHash(hash); + for (const block of this.blocks) block.updateHash(hash); + for (const variable of this.variables) variable.updateHash(hash); + } + + disconnect() { + for (const dep of this.dependencies) dep.disconnect(); + for (const block of this.blocks) block.disconnect(); + for (const variable of this.variables) variable.disconnect(); + } + + unseal() { + for (const block of this.blocks) block.unseal(); + } + + /** + * @param {DependencyFilterFunction} filter filter function for dependencies, gets passed all dependency ties from current instance + * @returns {boolean} returns boolean for filter + */ + hasDependencies(filter) { + if (filter) { + for (const dep of this.dependencies) { + if (filter(dep)) return true; + } + } else { + if (this.dependencies.length > 0) { + return true; + } + } + + for (const block of this.blocks) { + if (block.hasDependencies(filter)) return true; + } + for (const variable of this.variables) { + if (variable.hasDependencies(filter)) return true; + } + return false; + } + + sortItems() { + for (const block of this.blocks) block.sortItems(); + } +} + +module.exports = DependenciesBlock; diff --git a/node_modules/webpack/lib/DependenciesBlockVariable.js b/node_modules/webpack/lib/DependenciesBlockVariable.js index 0da641674..c4ed91627 100644 --- a/node_modules/webpack/lib/DependenciesBlockVariable.js +++ b/node_modules/webpack/lib/DependenciesBlockVariable.js @@ -1,51 +1,72 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const ReplaceSource = require("webpack-sources").ReplaceSource;
-const RawSource = require("webpack-sources").RawSource;
-
-class DependenciesBlockVariable {
- constructor(name, expression, dependencies) {
- this.name = name;
- this.expression = expression;
- this.dependencies = dependencies || [];
- }
-
- updateHash(hash) {
- hash.update(this.name);
- hash.update(this.expression);
- this.dependencies.forEach(d => {
- d.updateHash(hash);
- });
- }
-
- expressionSource(dependencyTemplates, outputOptions, requestShortener) {
- const source = new ReplaceSource(new RawSource(this.expression));
- this.dependencies.forEach(dep => {
- const template = dependencyTemplates.get(dep.constructor);
- if(!template) throw new Error(`No template for dependency: ${dep.constructor.name}`);
- template.apply(dep, source, outputOptions, requestShortener, dependencyTemplates);
- });
- return source;
- }
-
- disconnect() {
- this.dependencies.forEach(d => {
- d.disconnect();
- });
- }
-
- hasDependencies(filter) {
- if(filter) {
- if(this.dependencies.some(filter)) return true;
- } else {
- if(this.dependencies.length > 0) return true;
- }
- return false;
- }
-}
-
-module.exports = DependenciesBlockVariable;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const { RawSource, ReplaceSource } = require("webpack-sources"); + +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./Dependency").DependencyTemplate} DependencyTemplate */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("./util/createHash").Hash} Hash */ +/** @typedef {(d: Dependency) => boolean} DependencyFilterFunction */ +/** @typedef {Map<Function, DependencyTemplate>} DependencyTemplates */ + +class DependenciesBlockVariable { + /** + * Creates an instance of DependenciesBlockVariable. + * @param {string} name name of DependenciesBlockVariable + * @param {string} expression expression string + * @param {Dependency[]=} dependencies dependencies tied to this varaiable + */ + constructor(name, expression, dependencies) { + this.name = name; + this.expression = expression; + this.dependencies = dependencies || []; + } + + /** + * @param {Hash} hash hash for instance to update + * @returns {void} + */ + updateHash(hash) { + hash.update(this.name); + hash.update(this.expression); + for (const d of this.dependencies) { + d.updateHash(hash); + } + } + + /** + * @param {DependencyTemplates} dependencyTemplates Dependency constructors and templates Map. + * @param {RuntimeTemplate} runtimeTemplate runtimeTemplate to generate expression souce + * @returns {ReplaceSource} returns constructed source for expression via templates + */ + expressionSource(dependencyTemplates, runtimeTemplate) { + const source = new ReplaceSource(new RawSource(this.expression)); + for (const dep of this.dependencies) { + const template = dependencyTemplates.get(dep.constructor); + if (!template) { + throw new Error(`No template for dependency: ${dep.constructor.name}`); + } + template.apply(dep, source, runtimeTemplate, dependencyTemplates); + } + return source; + } + + disconnect() { + for (const d of this.dependencies) { + d.disconnect(); + } + } + + hasDependencies(filter) { + if (filter) { + return this.dependencies.some(filter); + } + return this.dependencies.length > 0; + } +} + +module.exports = DependenciesBlockVariable; diff --git a/node_modules/webpack/lib/Dependency.js b/node_modules/webpack/lib/Dependency.js index d9ebc287f..6d27b1ed6 100644 --- a/node_modules/webpack/lib/Dependency.js +++ b/node_modules/webpack/lib/Dependency.js @@ -1,54 +1,89 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const compareLocations = require("./compareLocations");
-
-class Dependency {
- constructor() {
- this.module = null;
- }
-
- isEqualResource() {
- return false;
- }
-
- // Returns the referenced module and export
- getReference() {
- if(!this.module) return null;
- return {
- module: this.module,
- importedNames: true, // true: full object, false: only sideeffects/no export, array of strings: the exports with this names
- };
- }
-
- // Returns the exported names
- getExports() {
- return null;
- }
-
- getWarnings() {
- return null;
- }
-
- getErrors() {
- return null;
- }
-
- updateHash(hash) {
- hash.update((this.module && this.module.id) + "");
- }
-
- disconnect() {
- this.module = null;
- }
-
- // TODO: remove in webpack 3
- compare(a, b) {
- return compareLocations(a.loc, b.loc);
- }
-}
-Dependency.compare = (a, b) => compareLocations(a.loc, b.loc);
-
-module.exports = Dependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const util = require("util"); +const compareLocations = require("./compareLocations"); +const DependencyReference = require("./dependencies/DependencyReference"); + +/** @typedef {import("./Module")} Module */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ + +/** + * @typedef {Object} DependencyTemplate + * @property {function(Dependency, Source, RuntimeTemplate, Map<Function, DependencyTemplate>): void} apply + */ + +/** @typedef {Object} SourcePosition + * @property {number} line + * @property {number=} column + */ + +/** @typedef {Object} RealDependencyLocation + * @property {SourcePosition} start + * @property {SourcePosition=} end + * @property {number=} index + */ + +/** @typedef {Object} SynteticDependencyLocation + * @property {string} name + * @property {number=} index + */ + +/** @typedef {SynteticDependencyLocation|RealDependencyLocation} DependencyLocation */ + +class Dependency { + constructor() { + /** @type {Module|null} */ + this.module = null; + // TODO remove in webpack 5 + /** @type {boolean} */ + this.weak = false; + /** @type {boolean} */ + this.optional = false; + /** @type {DependencyLocation} */ + this.loc = undefined; + } + + getResourceIdentifier() { + return null; + } + + // Returns the referenced module and export + getReference() { + if (!this.module) return null; + return new DependencyReference(this.module, true, this.weak); + } + + // Returns the exported names + getExports() { + return null; + } + + getWarnings() { + return null; + } + + getErrors() { + return null; + } + + updateHash(hash) { + hash.update((this.module && this.module.id) + ""); + } + + disconnect() { + this.module = null; + } +} + +// TODO remove in webpack 5 +Dependency.compare = util.deprecate( + (a, b) => compareLocations(a.loc, b.loc), + "Dependency.compare is deprecated and will be removed in the next major version" +); + +module.exports = Dependency; diff --git a/node_modules/webpack/lib/DllEntryPlugin.js b/node_modules/webpack/lib/DllEntryPlugin.js index 92b3c92c8..562628d90 100644 --- a/node_modules/webpack/lib/DllEntryPlugin.js +++ b/node_modules/webpack/lib/DllEntryPlugin.js @@ -1,37 +1,54 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const DllEntryDependency = require("./dependencies/DllEntryDependency");
-const SingleEntryDependency = require("./dependencies/SingleEntryDependency");
-const DllModuleFactory = require("./DllModuleFactory");
-
-class DllEntryPlugin {
- constructor(context, entries, name) {
- this.context = context;
- this.entries = entries;
- this.name = name;
- }
-
- apply(compiler) {
- compiler.plugin("compilation", (compilation, params) => {
- const dllModuleFactory = new DllModuleFactory();
- const normalModuleFactory = params.normalModuleFactory;
-
- compilation.dependencyFactories.set(DllEntryDependency, dllModuleFactory);
-
- compilation.dependencyFactories.set(SingleEntryDependency, normalModuleFactory);
- });
- compiler.plugin("make", (compilation, callback) => {
- compilation.addEntry(this.context, new DllEntryDependency(this.entries.map((e, idx) => {
- const dep = new SingleEntryDependency(e);
- dep.loc = `${this.name}:${idx}`;
- return dep;
- }), this.name), this.name, callback);
- });
- }
-}
-
-module.exports = DllEntryPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const DllEntryDependency = require("./dependencies/DllEntryDependency"); +const SingleEntryDependency = require("./dependencies/SingleEntryDependency"); +const DllModuleFactory = require("./DllModuleFactory"); + +class DllEntryPlugin { + constructor(context, entries, name) { + this.context = context; + this.entries = entries; + this.name = name; + } + + apply(compiler) { + compiler.hooks.compilation.tap( + "DllEntryPlugin", + (compilation, { normalModuleFactory }) => { + const dllModuleFactory = new DllModuleFactory(); + compilation.dependencyFactories.set( + DllEntryDependency, + dllModuleFactory + ); + compilation.dependencyFactories.set( + SingleEntryDependency, + normalModuleFactory + ); + } + ); + compiler.hooks.make.tapAsync("DllEntryPlugin", (compilation, callback) => { + compilation.addEntry( + this.context, + new DllEntryDependency( + this.entries.map((e, idx) => { + const dep = new SingleEntryDependency(e); + dep.loc = { + name: this.name, + index: idx + }; + return dep; + }), + this.name + ), + this.name, + callback + ); + }); + } +} + +module.exports = DllEntryPlugin; diff --git a/node_modules/webpack/lib/DllModule.js b/node_modules/webpack/lib/DllModule.js index 5e83129e9..0cd9cbcf8 100644 --- a/node_modules/webpack/lib/DllModule.js +++ b/node_modules/webpack/lib/DllModule.js @@ -1,58 +1,60 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
- */
-"use strict";
-
-const Module = require("./Module");
-const RawSource = require("webpack-sources").RawSource;
-
-class DllModule extends Module {
- constructor(context, dependencies, name, type) {
- super();
- this.context = context;
- this.dependencies = dependencies;
- this.name = name;
- this.built = false;
- this.cacheable = true;
- this.type = type;
- }
-
- identifier() {
- return `dll ${this.name}`;
- }
-
- readableIdentifier() {
- return `dll ${this.name}`;
- }
-
- disconnect() {
- this.built = false;
- super.disconnect();
- }
-
- build(options, compilation, resolver, fs, callback) {
- this.built = true;
- return callback();
- }
-
- source() {
- return new RawSource("module.exports = __webpack_require__;");
- }
-
- needRebuild() {
- return false;
- }
-
- size() {
- return 12;
- }
-
- updateHash(hash) {
- hash.update("dll module");
- hash.update(this.name || "");
- super.updateHash(hash);
- }
-}
-
-module.exports = DllModule;
+/* + 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"); + +/** @typedef {import("./util/createHash").Hash} Hash */ + +class DllModule extends Module { + constructor(context, dependencies, name, type) { + super("javascript/dynamic", context); + + // Info from Factory + this.dependencies = dependencies; + this.name = name; + this.type = type; + } + + identifier() { + return `dll ${this.name}`; + } + + readableIdentifier() { + return `dll ${this.name}`; + } + + build(options, compilation, resolver, fs, callback) { + this.built = true; + this.buildMeta = {}; + this.buildInfo = {}; + return callback(); + } + + source() { + return new RawSource("module.exports = __webpack_require__;"); + } + + needRebuild() { + return false; + } + + size() { + return 12; + } + + /** + * @param {Hash} hash the hash used to track dependencies + * @returns {void} + */ + updateHash(hash) { + hash.update("dll module"); + hash.update(this.name || ""); + super.updateHash(hash); + } +} + +module.exports = DllModule; diff --git a/node_modules/webpack/lib/DllModuleFactory.js b/node_modules/webpack/lib/DllModuleFactory.js index 7fba3126f..f5d12ddc4 100644 --- a/node_modules/webpack/lib/DllModuleFactory.js +++ b/node_modules/webpack/lib/DllModuleFactory.js @@ -1,20 +1,29 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const Tapable = require("tapable");
-const DllModule = require("./DllModule");
-
-class DllModuleFactory extends Tapable {
- constructor() {
- super();
- }
- create(data, callback) {
- const dependency = data.dependencies[0];
- callback(null, new DllModule(data.context, dependency.dependencies, dependency.name, dependency.type));
- }
-}
-
-module.exports = DllModuleFactory;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const { Tapable } = require("tapable"); +const DllModule = require("./DllModule"); + +class DllModuleFactory extends Tapable { + constructor() { + super(); + this.hooks = {}; + } + create(data, callback) { + const dependency = data.dependencies[0]; + callback( + null, + new DllModule( + data.context, + dependency.dependencies, + dependency.name, + dependency.type + ) + ); + } +} + +module.exports = DllModuleFactory; diff --git a/node_modules/webpack/lib/DllPlugin.js b/node_modules/webpack/lib/DllPlugin.js index 6fd929d6e..554283371 100644 --- a/node_modules/webpack/lib/DllPlugin.js +++ b/node_modules/webpack/lib/DllPlugin.js @@ -1,38 +1,44 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
- */
-"use strict";
-
-const DllEntryPlugin = require("./DllEntryPlugin");
-const LibManifestPlugin = require("./LibManifestPlugin");
-const FlagInitialModulesAsUsedPlugin = require("./FlagInitialModulesAsUsedPlugin");
-
-class DllPlugin {
- constructor(options) {
- this.options = options;
- }
-
- apply(compiler) {
- compiler.plugin("entry-option", (context, entry) => {
- function itemToPlugin(item, name) {
- if(Array.isArray(item))
- return new DllEntryPlugin(context, item, name);
- else
- throw new Error("DllPlugin: supply an Array as entry");
- }
- if(typeof entry === "object" && !Array.isArray(entry)) {
- Object.keys(entry).forEach(name => {
- compiler.apply(itemToPlugin(entry[name], name));
- });
- } else {
- compiler.apply(itemToPlugin(entry, "main"));
- }
- return true;
- });
- compiler.apply(new LibManifestPlugin(this.options));
- compiler.apply(new FlagInitialModulesAsUsedPlugin());
- }
-}
-
-module.exports = DllPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra + */ +"use strict"; + +const DllEntryPlugin = require("./DllEntryPlugin"); +const LibManifestPlugin = require("./LibManifestPlugin"); +const FlagInitialModulesAsUsedPlugin = require("./FlagInitialModulesAsUsedPlugin"); + +const validateOptions = require("schema-utils"); +const schema = require("../schemas/plugins/DllPlugin.json"); + +class DllPlugin { + constructor(options) { + validateOptions(schema, options, "Dll Plugin"); + this.options = options; + } + + apply(compiler) { + compiler.hooks.entryOption.tap("DllPlugin", (context, entry) => { + const itemToPlugin = (item, name) => { + if (Array.isArray(item)) { + return new DllEntryPlugin(context, item, name); + } + throw new Error("DllPlugin: supply an Array as entry"); + }; + if (typeof entry === "object" && !Array.isArray(entry)) { + Object.keys(entry).forEach(name => { + itemToPlugin(entry[name], name).apply(compiler); + }); + } else { + itemToPlugin(entry, "main").apply(compiler); + } + return true; + }); + new LibManifestPlugin(this.options).apply(compiler); + if (!this.options.entryOnly) { + new FlagInitialModulesAsUsedPlugin("DllPlugin").apply(compiler); + } + } +} + +module.exports = DllPlugin; diff --git a/node_modules/webpack/lib/DllReferencePlugin.js b/node_modules/webpack/lib/DllReferencePlugin.js index b0e386792..151862e5f 100644 --- a/node_modules/webpack/lib/DllReferencePlugin.js +++ b/node_modules/webpack/lib/DllReferencePlugin.js @@ -1,62 +1,132 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const DelegatedSourceDependency = require("./dependencies/DelegatedSourceDependency");
-const DelegatedModuleFactoryPlugin = require("./DelegatedModuleFactoryPlugin");
-const ExternalModuleFactoryPlugin = require("./ExternalModuleFactoryPlugin");
-const DelegatedExportsDependency = require("./dependencies/DelegatedExportsDependency");
-const NullFactory = require("./NullFactory");
-
-class DllReferencePlugin {
- constructor(options) {
- this.options = options;
- }
-
- apply(compiler) {
- compiler.plugin("compilation", (compilation, params) => {
- const normalModuleFactory = params.normalModuleFactory;
- compilation.dependencyFactories.set(DelegatedSourceDependency, normalModuleFactory);
- compilation.dependencyFactories.set(DelegatedExportsDependency, new NullFactory());
- });
-
- compiler.plugin("before-compile", (params, callback) => {
- const manifest = this.options.manifest;
- if(typeof manifest === "string") {
- params.compilationDependencies.push(manifest);
- compiler.inputFileSystem.readFile(manifest, function(err, result) {
- if(err) return callback(err);
- params["dll reference " + manifest] = JSON.parse(result.toString("utf-8"));
- return callback();
- });
- } else {
- return callback();
- }
- });
-
- compiler.plugin("compile", (params) => {
- let manifest = this.options.manifest;
- if(typeof manifest === "string") {
- manifest = params["dll reference " + manifest];
- }
- const name = this.options.name || manifest.name;
- const sourceType = this.options.sourceType || (manifest && manifest.type) || "var";
- const externals = {};
- const source = "dll-reference " + name;
- externals[source] = name;
- params.normalModuleFactory.apply(new ExternalModuleFactoryPlugin(sourceType, externals));
- params.normalModuleFactory.apply(new DelegatedModuleFactoryPlugin({
- source: source,
- type: this.options.type,
- scope: this.options.scope,
- context: this.options.context || compiler.options.context,
- content: this.options.content || manifest.content,
- extensions: this.options.extensions
- }));
- });
- }
-}
-
-module.exports = DllReferencePlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const parseJson = require("json-parse-better-errors"); +const DelegatedSourceDependency = require("./dependencies/DelegatedSourceDependency"); +const DelegatedModuleFactoryPlugin = require("./DelegatedModuleFactoryPlugin"); +const ExternalModuleFactoryPlugin = require("./ExternalModuleFactoryPlugin"); +const DelegatedExportsDependency = require("./dependencies/DelegatedExportsDependency"); +const NullFactory = require("./NullFactory"); +const makePathsRelative = require("./util/identifier").makePathsRelative; +const WebpackError = require("./WebpackError"); + +const validateOptions = require("schema-utils"); +const schema = require("../schemas/plugins/DllReferencePlugin.json"); + +class DllReferencePlugin { + constructor(options) { + validateOptions(schema, options, "Dll Reference Plugin"); + this.options = options; + } + + apply(compiler) { + compiler.hooks.compilation.tap( + "DllReferencePlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + DelegatedSourceDependency, + normalModuleFactory + ); + compilation.dependencyFactories.set( + DelegatedExportsDependency, + new NullFactory() + ); + } + ); + + compiler.hooks.beforeCompile.tapAsync( + "DllReferencePlugin", + (params, callback) => { + const manifest = this.options.manifest; + if (typeof manifest === "string") { + params.compilationDependencies.add(manifest); + compiler.inputFileSystem.readFile(manifest, (err, result) => { + if (err) return callback(err); + // Catch errors parsing the manifest so that blank + // or malformed manifest files don't kill the process. + try { + params["dll reference " + manifest] = parseJson( + result.toString("utf-8") + ); + } catch (e) { + // Store the error in the params so that it can + // be added as a compilation error later on. + const manifestPath = makePathsRelative( + compiler.options.context, + manifest + ); + params[ + "dll reference parse error " + manifest + ] = new DllManifestError(manifestPath, e.message); + } + return callback(); + }); + } else { + return callback(); + } + } + ); + + compiler.hooks.compile.tap("DllReferencePlugin", params => { + let manifest = this.options.manifest; + if (typeof manifest === "string") { + // 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 (params["dll reference parse error " + manifest]) { + return; + } + manifest = params["dll reference " + manifest]; + } + const name = this.options.name || manifest.name; + const sourceType = + this.options.sourceType || (manifest && manifest.type) || "var"; + const externals = {}; + const source = "dll-reference " + name; + externals[source] = name; + const normalModuleFactory = params.normalModuleFactory; + new ExternalModuleFactoryPlugin(sourceType, externals).apply( + normalModuleFactory + ); + new DelegatedModuleFactoryPlugin({ + source: source, + type: this.options.type, + scope: this.options.scope, + context: this.options.context || compiler.options.context, + content: this.options.content || manifest.content, + extensions: this.options.extensions + }).apply(normalModuleFactory); + }); + + compiler.hooks.compilation.tap( + "DllReferencePlugin", + (compilation, params) => { + let manifest = this.options.manifest; + if (typeof manifest === "string") { + // If there was an error parsing the manifest file, add the + // error as a compilation error to make the compilation fail. + let e = params["dll reference parse error " + manifest]; + if (e) { + compilation.errors.push(e); + } + } + } + ); + } +} + +class DllManifestError extends WebpackError { + constructor(filename, message) { + super(); + + this.name = "DllManifestError"; + this.message = `Dll manifest ${filename}\n${message}`; + + Error.captureStackTrace(this, this.constructor); + } +} + +module.exports = DllReferencePlugin; diff --git a/node_modules/webpack/lib/DynamicEntryPlugin.js b/node_modules/webpack/lib/DynamicEntryPlugin.js index 2079e1276..99c1be2bf 100644 --- a/node_modules/webpack/lib/DynamicEntryPlugin.js +++ b/node_modules/webpack/lib/DynamicEntryPlugin.js @@ -1,59 +1,93 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Naoyuki Kanezawa @nkzawa
-*/
-"use strict";
-
-const MultiEntryDependency = require("./dependencies/MultiEntryDependency");
-const SingleEntryDependency = require("./dependencies/SingleEntryDependency");
-const MultiModuleFactory = require("./MultiModuleFactory");
-const MultiEntryPlugin = require("./MultiEntryPlugin");
-const SingleEntryPlugin = require("./SingleEntryPlugin");
-
-class DynamicEntryPlugin {
- constructor(context, entry) {
- this.context = context;
- this.entry = entry;
- }
-
- apply(compiler) {
- compiler.plugin("compilation", (compilation, params) => {
- const multiModuleFactory = new MultiModuleFactory();
- const normalModuleFactory = params.normalModuleFactory;
-
- compilation.dependencyFactories.set(MultiEntryDependency, multiModuleFactory);
- compilation.dependencyFactories.set(SingleEntryDependency, normalModuleFactory);
- });
-
- compiler.plugin("make", (compilation, callback) => {
- const addEntry = (entry, name) => {
- const dep = DynamicEntryPlugin.createDependency(entry, name);
- return new Promise((resolve, reject) => {
- compilation.addEntry(this.context, dep, name, (err) => {
- if(err) return reject(err);
- resolve();
- });
- });
- };
-
- Promise.resolve(this.entry()).then((entry) => {
- if(typeof entry === "string" || Array.isArray(entry)) {
- addEntry(entry, "main").then(() => callback(), callback);
- } else if(typeof entry === "object") {
- Promise.all(Object.keys(entry).map((name) => {
- return addEntry(entry[name], name);
- })).then(() => callback(), callback);
- }
- });
- });
- }
-}
-
-module.exports = DynamicEntryPlugin;
-
-DynamicEntryPlugin.createDependency = function(entry, name) {
- if(Array.isArray(entry))
- return MultiEntryPlugin.createDependency(entry, name);
- else
- return SingleEntryPlugin.createDependency(entry, name);
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Naoyuki Kanezawa @nkzawa +*/ +"use strict"; + +const MultiEntryDependency = require("./dependencies/MultiEntryDependency"); +const SingleEntryDependency = require("./dependencies/SingleEntryDependency"); +const MultiModuleFactory = require("./MultiModuleFactory"); +const MultiEntryPlugin = require("./MultiEntryPlugin"); +const SingleEntryPlugin = require("./SingleEntryPlugin"); + +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Compiler").EntryOptionValuesFunction} EntryOptionValuesFunction */ + +class DynamicEntryPlugin { + /** + * @param {string} context the context path + * @param {EntryOptionValuesFunction} entry the entry value + */ + constructor(context, entry) { + this.context = context; + this.entry = entry; + } + + /** + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "DynamicEntryPlugin", + (compilation, { normalModuleFactory }) => { + const multiModuleFactory = new MultiModuleFactory(); + + compilation.dependencyFactories.set( + MultiEntryDependency, + multiModuleFactory + ); + compilation.dependencyFactories.set( + SingleEntryDependency, + normalModuleFactory + ); + } + ); + + compiler.hooks.make.tapAsync( + "DynamicEntryPlugin", + (compilation, callback) => { + /** + * @param {string|string[]} entry entry value or array of entry values + * @param {string} name name of entry + * @returns {Promise<any>} returns the promise resolving the Compilation#addEntry function + */ + const addEntry = (entry, name) => { + const dep = DynamicEntryPlugin.createDependency(entry, name); + return new Promise((resolve, reject) => { + compilation.addEntry(this.context, dep, name, err => { + if (err) return reject(err); + resolve(); + }); + }); + }; + + Promise.resolve(this.entry()).then(entry => { + if (typeof entry === "string" || Array.isArray(entry)) { + addEntry(entry, "main").then(() => callback(), callback); + } else if (typeof entry === "object") { + Promise.all( + Object.keys(entry).map(name => { + return addEntry(entry[name], name); + }) + ).then(() => callback(), callback); + } + }); + } + ); + } +} + +module.exports = DynamicEntryPlugin; +/** + * @param {string|string[]} entry entry value or array of entry paths + * @param {string} name name of entry + * @returns {SingleEntryDependency|MultiEntryDependency} returns dep + */ +DynamicEntryPlugin.createDependency = (entry, name) => { + if (Array.isArray(entry)) { + return MultiEntryPlugin.createDependency(entry, name); + } else { + return SingleEntryPlugin.createDependency(entry, name); + } +}; diff --git a/node_modules/webpack/lib/EntryModuleNotFoundError.js b/node_modules/webpack/lib/EntryModuleNotFoundError.js index d7b5d24fb..b2458d6f2 100644 --- a/node_modules/webpack/lib/EntryModuleNotFoundError.js +++ b/node_modules/webpack/lib/EntryModuleNotFoundError.js @@ -1,22 +1,21 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const WebpackError = require("./WebpackError");
-
-class EntryModuleNotFoundError extends WebpackError {
- constructor(err) {
- super();
-
- this.name = "EntryModuleNotFoundError";
- this.message = "Entry module not found: " + err;
- this.details = err.details;
- this.error = err;
-
- Error.captureStackTrace(this, this.constructor);
- }
-}
-
-module.exports = EntryModuleNotFoundError;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const WebpackError = require("./WebpackError"); + +class EntryModuleNotFoundError extends WebpackError { + constructor(err) { + super("Entry module not found: " + err); + + this.name = "EntryModuleNotFoundError"; + this.details = err.details; + this.error = err; + + Error.captureStackTrace(this, this.constructor); + } +} + +module.exports = EntryModuleNotFoundError; diff --git a/node_modules/webpack/lib/EntryOptionPlugin.js b/node_modules/webpack/lib/EntryOptionPlugin.js index 03692edd4..e992bc2c9 100644 --- a/node_modules/webpack/lib/EntryOptionPlugin.js +++ b/node_modules/webpack/lib/EntryOptionPlugin.js @@ -1,31 +1,45 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const SingleEntryPlugin = require("./SingleEntryPlugin");
-const MultiEntryPlugin = require("./MultiEntryPlugin");
-const DynamicEntryPlugin = require("./DynamicEntryPlugin");
-
-function itemToPlugin(context, item, name) {
- if(Array.isArray(item)) {
- return new MultiEntryPlugin(context, item, name);
- }
- return new SingleEntryPlugin(context, item, name);
-}
-
-module.exports = class EntryOptionPlugin {
- apply(compiler) {
- compiler.plugin("entry-option", (context, entry) => {
- if(typeof entry === "string" || Array.isArray(entry)) {
- compiler.apply(itemToPlugin(context, entry, "main"));
- } else if(typeof entry === "object") {
- Object.keys(entry).forEach(name => compiler.apply(itemToPlugin(context, entry[name], name)));
- } else if(typeof entry === "function") {
- compiler.apply(new DynamicEntryPlugin(context, entry));
- }
- return true;
- });
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const SingleEntryPlugin = require("./SingleEntryPlugin"); +const MultiEntryPlugin = require("./MultiEntryPlugin"); +const DynamicEntryPlugin = require("./DynamicEntryPlugin"); + +/** @typedef {import("./Compiler")} Compiler */ + +/** + * @param {string} context context path + * @param {string | string[]} item entry array or single path + * @param {string} name entry key name + * @returns {SingleEntryPlugin | MultiEntryPlugin} returns either a single or multi entry plugin + */ +const itemToPlugin = (context, item, name) => { + if (Array.isArray(item)) { + return new MultiEntryPlugin(context, item, name); + } + return new SingleEntryPlugin(context, item, name); +}; + +module.exports = class EntryOptionPlugin { + /** + * @param {Compiler} compiler the compiler instance one is tapping into + * @returns {void} + */ + apply(compiler) { + compiler.hooks.entryOption.tap("EntryOptionPlugin", (context, entry) => { + if (typeof entry === "string" || Array.isArray(entry)) { + itemToPlugin(context, entry, "main").apply(compiler); + } else if (typeof entry === "object") { + for (const name of Object.keys(entry)) { + itemToPlugin(context, entry[name], name).apply(compiler); + } + } else if (typeof entry === "function") { + new DynamicEntryPlugin(context, entry).apply(compiler); + } + return true; + }); + } +}; diff --git a/node_modules/webpack/lib/Entrypoint.js b/node_modules/webpack/lib/Entrypoint.js index 04dc2084b..c67ff44ed 100644 --- a/node_modules/webpack/lib/Entrypoint.js +++ b/node_modules/webpack/lib/Entrypoint.js @@ -1,43 +1,54 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-class Entrypoint {
- constructor(name) {
- this.name = name;
- this.chunks = [];
- }
-
- unshiftChunk(chunk) {
- this.chunks.unshift(chunk);
- chunk.entrypoints.push(this);
- }
-
- insertChunk(chunk, before) {
- const idx = this.chunks.indexOf(before);
- if(idx >= 0) {
- this.chunks.splice(idx, 0, chunk);
- } else {
- throw new Error("before chunk not found");
- }
- chunk.entrypoints.push(this);
- }
-
- getFiles() {
- const files = [];
-
- for(let chunkIdx = 0; chunkIdx < this.chunks.length; chunkIdx++) {
- for(let fileIdx = 0; fileIdx < this.chunks[chunkIdx].files.length; fileIdx++) {
- if(files.indexOf(this.chunks[chunkIdx].files[fileIdx]) === -1) {
- files.push(this.chunks[chunkIdx].files[fileIdx]);
- }
- }
- }
-
- return files;
- }
-}
-
-module.exports = Entrypoint;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const ChunkGroup = require("./ChunkGroup"); + +/** @typedef {import("./Chunk")} Chunk */ + +/** + * 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 {string} name the name of the entrypoint + */ + constructor(name) { + super(name); + /** @type {Chunk=} */ + this.runtimeChunk = undefined; + } + + /** + * isInitial will always return true for Entrypoint ChunkGroup. + * @returns {true} returns true as all entrypoints are initial ChunkGroups + */ + isInitial() { + return true; + } + + /** + * 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} returns the runtime chunk or first chunk in `this.chunks` + */ + getRuntimeChunk() { + return this.runtimeChunk || this.chunks[0]; + } +} + +module.exports = Entrypoint; diff --git a/node_modules/webpack/lib/EnvironmentPlugin.js b/node_modules/webpack/lib/EnvironmentPlugin.js index 3f03fabdf..c9fafaa8a 100644 --- a/node_modules/webpack/lib/EnvironmentPlugin.js +++ b/node_modules/webpack/lib/EnvironmentPlugin.js @@ -1,50 +1,72 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Authors Simen Brekken @simenbrekken, Einar Löve @einarlove
-*/
-
-"use strict";
-
-const DefinePlugin = require("./DefinePlugin");
-
-class EnvironmentPlugin {
- constructor(keys) {
- if(Array.isArray(keys)) {
- this.keys = keys;
- this.defaultValues = {};
- } else if(keys && typeof keys === "object") {
- this.keys = Object.keys(keys);
- this.defaultValues = keys;
- } else {
- this.keys = Array.prototype.slice.call(arguments);
- this.defaultValues = {};
- }
- }
-
- apply(compiler) {
- const definitions = this.keys.reduce((defs, key) => {
- const value = process.env[key] !== undefined ? process.env[key] : this.defaultValues[key];
-
- if(value === undefined) {
- compiler.plugin("this-compilation", compilation => {
- const error = new Error(
- `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.warnings.push(error);
- });
- }
-
- defs[`process.env.${key}`] = typeof value === "undefined" ? "undefined" : JSON.stringify(value);
-
- return defs;
- }, {});
-
- compiler.apply(new DefinePlugin(definitions));
- }
-}
-
-module.exports = EnvironmentPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Authors Simen Brekken @simenbrekken, Einar Löve @einarlove +*/ + +"use strict"; + +/** @typedef {import("./Compiler")} Compiler */ + +const WebpackError = require("./WebpackError"); +const DefinePlugin = require("./DefinePlugin"); + +const needsEnvVarFix = + ["8", "9"].indexOf(process.versions.node.split(".")[0]) >= 0 && + process.platform === "win32"; + +class EnvironmentPlugin { + 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 = keys[0]; + } else { + this.keys = keys; + this.defaultValues = {}; + } + } + + /** + * @param {Compiler} compiler webpack compiler instance + * @returns {void} + */ + apply(compiler) { + const definitions = this.keys.reduce((defs, key) => { + // TODO remove once the fix has made its way into Node 8. + // Work around https://github.com/nodejs/node/pull/18463, + // affecting Node 8 & 9 by performing an OS-level + // operation that always succeeds before reading + // environment variables: + if (needsEnvVarFix) require("os").cpus(); + + 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.warnings.push(error); + }); + } + + defs[`process.env.${key}`] = + value === undefined ? "undefined" : JSON.stringify(value); + + return defs; + }, {}); + + new DefinePlugin(definitions).apply(compiler); + } +} + +module.exports = EnvironmentPlugin; diff --git a/node_modules/webpack/lib/ErrorHelpers.js b/node_modules/webpack/lib/ErrorHelpers.js index 527e0ed21..900ae4d59 100644 --- a/node_modules/webpack/lib/ErrorHelpers.js +++ b/node_modules/webpack/lib/ErrorHelpers.js @@ -1,31 +1,60 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const loaderFlag = "LOADER_EXECUTION";
-
-exports.cutOffLoaderExecution = (stack) => {
- stack = stack.split("\n");
- for(let i = 0; i < stack.length; i++)
- if(stack[i].indexOf(loaderFlag) >= 0)
- stack.length = i;
- return stack.join("\n");
-};
-
-exports.cutOffMessage = (stack, message) => {
- const nextLine = stack.indexOf("\n");
- if(nextLine === -1) {
- return stack === message ? "" : stack;
- } else {
- const firstLine = stack.substr(0, nextLine);
- return firstLine === message ? stack.substr(nextLine + 1) : stack;
- }
-};
-
-exports.cleanUp = (stack, message) => {
- stack = exports.cutOffLoaderExecution(stack);
- stack = exports.cutOffMessage(stack, message);
- return stack;
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const loaderFlag = "LOADER_EXECUTION"; + +const webpackOptionsFlag = "WEBPACK_OPTIONS"; + +exports.cutOffByFlag = (stack, flag) => { + stack = stack.split("\n"); + for (let i = 0; i < stack.length; i++) { + if (stack[i].includes(flag)) { + stack.length = i; + } + } + return stack.join("\n"); +}; + +exports.cutOffLoaderExecution = stack => + exports.cutOffByFlag(stack, loaderFlag); + +exports.cutOffWebpackOptions = stack => + exports.cutOffByFlag(stack, webpackOptionsFlag); + +exports.cutOffMultilineMessage = (stack, message) => { + stack = stack.split("\n"); + message = message.split("\n"); + + return stack + .reduce( + (acc, line, idx) => + line.includes(message[idx]) ? acc : acc.concat(line), + [] + ) + .join("\n"); +}; + +exports.cutOffMessage = (stack, message) => { + const nextLine = stack.indexOf("\n"); + if (nextLine === -1) { + return stack === message ? "" : stack; + } else { + const firstLine = stack.substr(0, nextLine); + return firstLine === message ? stack.substr(nextLine + 1) : stack; + } +}; + +exports.cleanUp = (stack, message) => { + stack = exports.cutOffLoaderExecution(stack); + stack = exports.cutOffMessage(stack, message); + return stack; +}; + +exports.cleanUpWebpackOptions = (stack, message) => { + stack = exports.cutOffWebpackOptions(stack); + stack = exports.cutOffMultilineMessage(stack, message); + return stack; +}; diff --git a/node_modules/webpack/lib/EvalDevToolModulePlugin.js b/node_modules/webpack/lib/EvalDevToolModulePlugin.js index 69f1e9d85..2af11f9c3 100644 --- a/node_modules/webpack/lib/EvalDevToolModulePlugin.js +++ b/node_modules/webpack/lib/EvalDevToolModulePlugin.js @@ -1,22 +1,27 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const EvalDevToolModuleTemplatePlugin = require("./EvalDevToolModuleTemplatePlugin");
-
-class EvalDevToolModulePlugin {
- constructor(sourceUrlComment, moduleFilenameTemplate) {
- this.sourceUrlComment = sourceUrlComment;
- this.moduleFilenameTemplate = moduleFilenameTemplate;
- }
-
- apply(compiler) {
- compiler.plugin("compilation", (compilation) => {
- compilation.moduleTemplate.apply(new EvalDevToolModuleTemplatePlugin(this.sourceUrlComment, this.moduleFilenameTemplate));
- });
- }
-}
-
-module.exports = EvalDevToolModulePlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const EvalDevToolModuleTemplatePlugin = require("./EvalDevToolModuleTemplatePlugin"); + +class EvalDevToolModulePlugin { + constructor(options) { + this.sourceUrlComment = options.sourceUrlComment; + this.moduleFilenameTemplate = options.moduleFilenameTemplate; + this.namespace = options.namespace; + } + + apply(compiler) { + compiler.hooks.compilation.tap("EvalDevToolModulePlugin", compilation => { + new EvalDevToolModuleTemplatePlugin({ + sourceUrlComment: this.sourceUrlComment, + moduleFilenameTemplate: this.moduleFilenameTemplate, + namespace: this.namespace + }).apply(compilation.moduleTemplates.javascript); + }); + } +} + +module.exports = EvalDevToolModulePlugin; diff --git a/node_modules/webpack/lib/EvalDevToolModuleTemplatePlugin.js b/node_modules/webpack/lib/EvalDevToolModuleTemplatePlugin.js index e56970ce9..ab5dd1aac 100644 --- a/node_modules/webpack/lib/EvalDevToolModuleTemplatePlugin.js +++ b/node_modules/webpack/lib/EvalDevToolModuleTemplatePlugin.js @@ -1,33 +1,61 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const RawSource = require("webpack-sources").RawSource;
-const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
-
-class EvalDevToolModuleTemplatePlugin {
- constructor(sourceUrlComment, moduleFilenameTemplate) {
- this.sourceUrlComment = sourceUrlComment || "\n//# sourceURL=[url]";
- this.moduleFilenameTemplate = moduleFilenameTemplate || "webpack:///[resourcePath]?[loaders]";
- }
-
- apply(moduleTemplate) {
- moduleTemplate.plugin("module", (source, module) => {
- const content = source.source();
- const str = ModuleFilenameHelpers.createFilename(module, this.moduleFilenameTemplate, moduleTemplate.requestShortener);
- const footer = ["\n",
- ModuleFilenameHelpers.createFooter(module, moduleTemplate.requestShortener),
- this.sourceUrlComment.replace(/\[url\]/g, encodeURI(str).replace(/%2F/g, "/").replace(/%20/g, "_").replace(/%5E/g, "^").replace(/%5C/g, "\\").replace(/^\//, ""))
- ].join("\n");
- return new RawSource(`eval(${JSON.stringify(content + footer)});`);
- });
- moduleTemplate.plugin("hash", hash => {
- hash.update("EvalDevToolModuleTemplatePlugin");
- hash.update("2");
- });
- }
-}
-
-module.exports = EvalDevToolModuleTemplatePlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const { RawSource } = require("webpack-sources"); +const ModuleFilenameHelpers = require("./ModuleFilenameHelpers"); + +const cache = new WeakMap(); + +class EvalDevToolModuleTemplatePlugin { + constructor(options) { + this.sourceUrlComment = options.sourceUrlComment || "\n//# sourceURL=[url]"; + this.moduleFilenameTemplate = + options.moduleFilenameTemplate || + "webpack://[namespace]/[resourcePath]?[loaders]"; + this.namespace = options.namespace || ""; + } + + apply(moduleTemplate) { + moduleTemplate.hooks.module.tap( + "EvalDevToolModuleTemplatePlugin", + (source, module) => { + const cacheEntry = cache.get(source); + if (cacheEntry !== undefined) return cacheEntry; + const content = source.source(); + const str = ModuleFilenameHelpers.createFilename( + module, + { + moduleFilenameTemplate: this.moduleFilenameTemplate, + namespace: this.namespace + }, + moduleTemplate.runtimeTemplate.requestShortener + ); + 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(${JSON.stringify(content + footer)});` + ); + cache.set(source, result); + return result; + } + ); + moduleTemplate.hooks.hash.tap("EvalDevToolModuleTemplatePlugin", hash => { + hash.update("EvalDevToolModuleTemplatePlugin"); + hash.update("2"); + }); + } +} + +module.exports = EvalDevToolModuleTemplatePlugin; diff --git a/node_modules/webpack/lib/EvalSourceMapDevToolModuleTemplatePlugin.js b/node_modules/webpack/lib/EvalSourceMapDevToolModuleTemplatePlugin.js index 944266b8f..ac22c6897 100644 --- a/node_modules/webpack/lib/EvalSourceMapDevToolModuleTemplatePlugin.js +++ b/node_modules/webpack/lib/EvalSourceMapDevToolModuleTemplatePlugin.js @@ -1,75 +1,115 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const RawSource = require("webpack-sources").RawSource;
-const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
-
-class EvalSourceMapDevToolModuleTemplatePlugin {
- constructor(compilation, options) {
- this.compilation = compilation;
- this.sourceMapComment = options.append || "//# sourceURL=[module]\n//# sourceMappingURL=[url]";
- this.moduleFilenameTemplate = options.moduleFilenameTemplate || "webpack:///[resource-path]?[hash]";
- this.options = options;
- }
-
- apply(moduleTemplate) {
- const self = this;
- const options = this.options;
- moduleTemplate.plugin("module", function(source, module) {
- if(source.__EvalSourceMapDevToolData)
- return source.__EvalSourceMapDevToolData;
- let sourceMap;
- let content;
- if(source.sourceAndMap) {
- const sourceAndMap = source.sourceAndMap(options);
- sourceMap = sourceAndMap.map;
- content = sourceAndMap.source;
- } else {
- sourceMap = source.map(options);
- content = source.source();
- }
- if(!sourceMap) {
- return source;
- }
-
- // Clone (flat) the sourcemap to ensure that the mutations below do not persist.
- sourceMap = Object.keys(sourceMap).reduce(function(obj, key) {
- obj[key] = sourceMap[key];
- return obj;
- }, {});
- const modules = sourceMap.sources.map(function(source) {
- const module = self.compilation.findModule(source);
- return module || source;
- });
- let moduleFilenames = modules.map(function(module) {
- return ModuleFilenameHelpers.createFilename(module, self.moduleFilenameTemplate, this.requestShortener);
- }, this);
- moduleFilenames = ModuleFilenameHelpers.replaceDuplicates(moduleFilenames, function(filename, i, n) {
- for(let j = 0; j < n; j++)
- filename += "*";
- return filename;
- });
- sourceMap.sources = moduleFilenames;
- if(sourceMap.sourcesContent) {
- sourceMap.sourcesContent = sourceMap.sourcesContent.map(function(content, i) {
- return typeof content === "string" ? `${content}\n\n\n${ModuleFilenameHelpers.createFooter(modules[i], this.requestShortener)}` : null;
- }, this);
- }
- sourceMap.sourceRoot = options.sourceRoot || "";
- sourceMap.file = `${module.id}.js`;
-
- const footer = self.sourceMapComment.replace(/\[url\]/g, `data:application/json;charset=utf-8;base64,${new Buffer(JSON.stringify(sourceMap), "utf8").toString("base64")}`) + //eslint-disable-line
- `\n//# sourceURL=webpack-internal:///${module.id}\n`; // workaround for chrome bug
- source.__EvalSourceMapDevToolData = new RawSource(`eval(${JSON.stringify(content + footer)});`);
- return source.__EvalSourceMapDevToolData;
- });
- moduleTemplate.plugin("hash", function(hash) {
- hash.update("eval-source-map");
- hash.update("2");
- });
- }
-}
-module.exports = EvalSourceMapDevToolModuleTemplatePlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const { RawSource } = require("webpack-sources"); +const ModuleFilenameHelpers = require("./ModuleFilenameHelpers"); + +const cache = new WeakMap(); + +class EvalSourceMapDevToolModuleTemplatePlugin { + constructor(compilation, options) { + this.compilation = compilation; + this.sourceMapComment = + options.append || "//# sourceURL=[module]\n//# sourceMappingURL=[url]"; + this.moduleFilenameTemplate = + options.moduleFilenameTemplate || + "webpack://[namespace]/[resource-path]?[hash]"; + this.namespace = options.namespace || ""; + this.options = options; + } + + apply(moduleTemplate) { + const self = this; + const options = this.options; + const matchModule = ModuleFilenameHelpers.matchObject.bind( + ModuleFilenameHelpers, + options + ); + moduleTemplate.hooks.module.tap( + "EvalSourceMapDevToolModuleTemplatePlugin", + (source, module) => { + const cachedSource = cache.get(source); + if (cachedSource !== undefined) { + return cachedSource; + } + + if (!matchModule(module.resource)) { + return source; + } + + /** @type {{ [key: string]: TODO; }} */ + let sourceMap; + let content; + if (source.sourceAndMap) { + const sourceAndMap = source.sourceAndMap(options); + sourceMap = sourceAndMap.map; + content = sourceAndMap.source; + } else { + sourceMap = source.map(options); + content = source.source(); + } + if (!sourceMap) { + return source; + } + + // Clone (flat) the sourcemap to ensure that the mutations below do not persist. + sourceMap = Object.keys(sourceMap).reduce((obj, key) => { + obj[key] = sourceMap[key]; + return obj; + }, {}); + const modules = sourceMap.sources.map(source => { + const module = self.compilation.findModule(source); + return module || source; + }); + let moduleFilenames = modules.map(module => { + return ModuleFilenameHelpers.createFilename( + module, + { + moduleFilenameTemplate: self.moduleFilenameTemplate, + namespace: self.namespace + }, + moduleTemplate.runtimeTemplate.requestShortener + ); + }); + moduleFilenames = ModuleFilenameHelpers.replaceDuplicates( + moduleFilenames, + (filename, i, n) => { + for (let j = 0; j < n; j++) filename += "*"; + return filename; + } + ); + sourceMap.sources = moduleFilenames; + sourceMap.sourceRoot = options.sourceRoot || ""; + sourceMap.file = `${module.id}.js`; + + const footer = + self.sourceMapComment.replace( + /\[url\]/g, + `data:application/json;charset=utf-8;base64,${Buffer.from( + JSON.stringify(sourceMap), + "utf8" + ).toString("base64")}` + ) + `\n//# sourceURL=webpack-internal:///${module.id}\n`; // workaround for chrome bug + + const evalSource = new RawSource( + `eval(${JSON.stringify(content + footer)});` + ); + + cache.set(source, evalSource); + + return evalSource; + } + ); + moduleTemplate.hooks.hash.tap( + "EvalSourceMapDevToolModuleTemplatePlugin", + hash => { + hash.update("eval-source-map"); + hash.update("2"); + } + ); + } +} +module.exports = EvalSourceMapDevToolModuleTemplatePlugin; diff --git a/node_modules/webpack/lib/EvalSourceMapDevToolPlugin.js b/node_modules/webpack/lib/EvalSourceMapDevToolPlugin.js index 1a2aed396..daf9aaddf 100644 --- a/node_modules/webpack/lib/EvalSourceMapDevToolPlugin.js +++ b/node_modules/webpack/lib/EvalSourceMapDevToolPlugin.js @@ -1,32 +1,41 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const EvalSourceMapDevToolModuleTemplatePlugin = require("./EvalSourceMapDevToolModuleTemplatePlugin");
-const SourceMapDevToolModuleOptionsPlugin = require("./SourceMapDevToolModuleOptionsPlugin");
-
-class EvalSourceMapDevToolPlugin {
- constructor(options) {
- if(arguments.length > 1)
- throw new Error("EvalSourceMapDevToolPlugin only takes one argument (pass an options object)");
- if(typeof options === "string") {
- options = {
- append: options
- };
- }
- if(!options) options = {};
- this.options = options;
- }
-
- apply(compiler) {
- const options = this.options;
- compiler.plugin("compilation", (compilation) => {
- new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation);
- compilation.moduleTemplate.apply(new EvalSourceMapDevToolModuleTemplatePlugin(compilation, options));
- });
- }
-}
-
-module.exports = EvalSourceMapDevToolPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const EvalSourceMapDevToolModuleTemplatePlugin = require("./EvalSourceMapDevToolModuleTemplatePlugin"); +const SourceMapDevToolModuleOptionsPlugin = require("./SourceMapDevToolModuleOptionsPlugin"); + +class EvalSourceMapDevToolPlugin { + constructor(options) { + if (arguments.length > 1) { + throw new Error( + "EvalSourceMapDevToolPlugin only takes one argument (pass an options object)" + ); + } + if (typeof options === "string") { + options = { + append: options + }; + } + if (!options) options = {}; + this.options = options; + } + + apply(compiler) { + const options = this.options; + compiler.hooks.compilation.tap( + "EvalSourceMapDevToolPlugin", + compilation => { + new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation); + new EvalSourceMapDevToolModuleTemplatePlugin( + compilation, + options + ).apply(compilation.moduleTemplates.javascript); + } + ); + } +} + +module.exports = EvalSourceMapDevToolPlugin; diff --git a/node_modules/webpack/lib/ExportPropertyMainTemplatePlugin.js b/node_modules/webpack/lib/ExportPropertyMainTemplatePlugin.js index 8dd80901e..90df031aa 100644 --- a/node_modules/webpack/lib/ExportPropertyMainTemplatePlugin.js +++ b/node_modules/webpack/lib/ExportPropertyMainTemplatePlugin.js @@ -1,31 +1,53 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const ConcatSource = require("webpack-sources").ConcatSource;
-
-function accessorToObjectAccess(accessor) {
- return accessor.map(a => `[${JSON.stringify(a)}]`).join("");
-}
-
-class ExportPropertyMainTemplatePlugin {
- constructor(property) {
- this.property = property;
- }
-
- apply(compilation) {
- const mainTemplate = compilation.mainTemplate;
- compilation.templatesPlugin("render-with-entry", (source, chunk, hash) => {
- const postfix = `${accessorToObjectAccess([].concat(this.property))}`;
- return new ConcatSource(source, postfix);
- });
- mainTemplate.plugin("hash", hash => {
- hash.update("export property");
- hash.update(`${this.property}`);
- });
- }
-}
-
-module.exports = ExportPropertyMainTemplatePlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const { ConcatSource } = require("webpack-sources"); + +/** @typedef {import("./Compilation")} Compilation */ + +/** + * @param {string[]} accessor the accessor to convert to path + * @returns {string} the path + */ +const accessorToObjectAccess = accessor => { + return accessor.map(a => `[${JSON.stringify(a)}]`).join(""); +}; + +class ExportPropertyMainTemplatePlugin { + /** + * @param {string|string[]} property the name of the property to export + */ + constructor(property) { + this.property = property; + } + + /** + * @param {Compilation} compilation the compilation instance + * @returns {void} + */ + apply(compilation) { + const { mainTemplate, chunkTemplate } = compilation; + + const onRenderWithEntry = (source, chunk, hash) => { + const postfix = `${accessorToObjectAccess([].concat(this.property))}`; + return new ConcatSource(source, postfix); + }; + + for (const template of [mainTemplate, chunkTemplate]) { + template.hooks.renderWithEntry.tap( + "ExportPropertyMainTemplatePlugin", + onRenderWithEntry + ); + } + + mainTemplate.hooks.hash.tap("ExportPropertyMainTemplatePlugin", hash => { + hash.update("export property"); + hash.update(`${this.property}`); + }); + } +} + +module.exports = ExportPropertyMainTemplatePlugin; diff --git a/node_modules/webpack/lib/ExtendedAPIPlugin.js b/node_modules/webpack/lib/ExtendedAPIPlugin.js index 5b0b913d4..e41defb1f 100644 --- a/node_modules/webpack/lib/ExtendedAPIPlugin.js +++ b/node_modules/webpack/lib/ExtendedAPIPlugin.js @@ -1,47 +1,88 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const ConstDependency = require("./dependencies/ConstDependency");
-const ParserHelpers = require("./ParserHelpers");
-const NullFactory = require("./NullFactory");
-
-const REPLACEMENTS = {
- __webpack_hash__: "__webpack_require__.h", // eslint-disable-line camelcase
- __webpack_chunkname__: "__webpack_require__.cn" // eslint-disable-line camelcase
-};
-const REPLACEMENT_TYPES = {
- __webpack_hash__: "string", // eslint-disable-line camelcase
- __webpack_chunkname__: "string" // eslint-disable-line camelcase
-};
-
-class ExtendedAPIPlugin {
- apply(compiler) {
- compiler.plugin("compilation", (compilation, params) => {
- compilation.dependencyFactories.set(ConstDependency, new NullFactory());
- compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
- compilation.mainTemplate.plugin("require-extensions", function(source, chunk, hash) {
- const buf = [source];
- buf.push("");
- buf.push("// __webpack_hash__");
- buf.push(`${this.requireFn}.h = ${JSON.stringify(hash)};`);
- buf.push("");
- buf.push("// __webpack_chunkname__");
- buf.push(`${this.requireFn}.cn = ${JSON.stringify(chunk.name)};`);
- return this.asString(buf);
- });
- compilation.mainTemplate.plugin("global-hash", () => true);
-
- params.normalModuleFactory.plugin("parser", (parser, parserOptions) => {
- Object.keys(REPLACEMENTS).forEach(key => {
- parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
- parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
- });
- });
- });
- }
-}
-
-module.exports = ExtendedAPIPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Template = require("./Template"); +const ConstDependency = require("./dependencies/ConstDependency"); +const ParserHelpers = require("./ParserHelpers"); +const NullFactory = require("./NullFactory"); + +const REPLACEMENTS = { + // eslint-disable-next-line camelcase + __webpack_hash__: "__webpack_require__.h", + // eslint-disable-next-line camelcase + __webpack_chunkname__: "__webpack_require__.cn" +}; +const REPLACEMENT_TYPES = { + // eslint-disable-next-line camelcase + __webpack_hash__: "string", + // eslint-disable-next-line camelcase + __webpack_chunkname__: "string" +}; + +class ExtendedAPIPlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "ExtendedAPIPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set(ConstDependency, new NullFactory()); + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); + + const mainTemplate = compilation.mainTemplate; + mainTemplate.hooks.requireExtensions.tap( + "ExtendedAPIPlugin", + (source, chunk, hash) => { + const buf = [source]; + buf.push(""); + buf.push("// __webpack_hash__"); + buf.push(`${mainTemplate.requireFn}.h = ${JSON.stringify(hash)};`); + buf.push(""); + buf.push("// __webpack_chunkname__"); + buf.push( + `${mainTemplate.requireFn}.cn = ${JSON.stringify(chunk.name)};` + ); + return Template.asString(buf); + } + ); + mainTemplate.hooks.globalHash.tap("ExtendedAPIPlugin", () => true); + + const handler = (parser, parserOptions) => { + Object.keys(REPLACEMENTS).forEach(key => { + parser.hooks.expression + .for(key) + .tap( + "ExtendedAPIPlugin", + ParserHelpers.toConstantDependencyWithWebpackRequire( + parser, + REPLACEMENTS[key] + ) + ); + parser.hooks.evaluateTypeof + .for(key) + .tap( + "ExtendedAPIPlugin", + ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]) + ); + }); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("ExtendedAPIPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("ExtendedAPIPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("ExtendedAPIPlugin", handler); + } + ); + } +} + +module.exports = ExtendedAPIPlugin; diff --git a/node_modules/webpack/lib/ExternalModule.js b/node_modules/webpack/lib/ExternalModule.js index 45c183b1a..8cb5e071c 100644 --- a/node_modules/webpack/lib/ExternalModule.js +++ b/node_modules/webpack/lib/ExternalModule.js @@ -1,128 +1,177 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const Module = require("./Module");
-const OriginalSource = require("webpack-sources").OriginalSource;
-const RawSource = require("webpack-sources").RawSource;
-const WebpackMissingModule = require("./dependencies/WebpackMissingModule");
-const Template = require("./Template");
-
-class ExternalModule extends Module {
- constructor(request, type, userRequest) {
- super();
- this.request = request;
- this.userRequest = userRequest;
- this.type = type;
- this.built = false;
- this.external = true;
- }
-
- libIdent() {
- return this.userRequest;
- }
-
- chunkCondition(chunk) {
- return chunk.hasEntryModule();
- }
-
- identifier() {
- return "external " + JSON.stringify(this.request);
- }
-
- readableIdentifier() {
- return "external " + JSON.stringify(this.request);
- }
-
- needRebuild() {
- return false;
- }
-
- build(options, compilation, resolver, fs, callback) {
- this.builtTime = Date.now();
- callback();
- }
-
- 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 `(function() { module.exports = ${type}${objectLookup}; }());`;
- }
-
- getSourceForCommonJsExternal(moduleAndSpecifiers) {
- if(!Array.isArray(moduleAndSpecifiers)) {
- return `module.exports = require(${JSON.stringify(moduleAndSpecifiers)});`;
- }
-
- const moduleName = moduleAndSpecifiers[0];
- const objectLookup = moduleAndSpecifiers.slice(1).map(r => `[${JSON.stringify(r)}]`).join("");
- return `module.exports = require(${moduleName})${objectLookup};`;
- }
-
- checkExternalVariable(variableToCheck, request) {
- return `if(typeof ${variableToCheck} === 'undefined') {${WebpackMissingModule.moduleCode(request)}}\n`;
- }
-
- getSourceForAmdOrUmdExternal(id, optional, request) {
- const externalVariable = Template.toIdentifier(`__WEBPACK_EXTERNAL_MODULE_${id}__`);
- const missingModuleError = optional ? this.checkExternalVariable(externalVariable, request) : "";
- return `${missingModuleError}module.exports = ${externalVariable};`;
- }
-
- getSourceForDefaultCase(optional, request) {
- const missingModuleError = optional ? this.checkExternalVariable(request, request) : "";
- return `${missingModuleError}module.exports = ${request};`;
- }
-
- getSourceString() {
- const request = typeof this.request === "object" ? this.request[this.type] : this.request;
- switch(this.type) {
- case "this":
- case "window":
- case "global":
- return this.getSourceForGlobalVariableExternal(request, this.type);
- case "commonjs":
- case "commonjs2":
- return this.getSourceForCommonJsExternal(request);
- case "amd":
- case "umd":
- case "umd2":
- return this.getSourceForAmdOrUmdExternal(this.id, this.optional, request);
- default:
- return this.getSourceForDefaultCase(this.optional, request);
- }
- }
-
- getSource(sourceString) {
- if(this.useSourceMap) {
- return new OriginalSource(sourceString, this.identifier());
- }
-
- return new RawSource(sourceString);
- }
-
- source() {
- return this.getSource(
- this.getSourceString()
- );
- }
-
- size() {
- return 42;
- }
-
- updateHash(hash) {
- hash.update(this.type);
- hash.update(JSON.stringify(this.request));
- hash.update(JSON.stringify(Boolean(this.optional)));
- super.updateHash(hash);
- }
-}
-
-module.exports = ExternalModule;
+/* + 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 WebpackMissingModule = require("./dependencies/WebpackMissingModule"); +const Template = require("./Template"); + +/** @typedef {import("./util/createHash").Hash} Hash */ + +class ExternalModule extends Module { + constructor(request, type, userRequest) { + super("javascript/dynamic", null); + + // Info from Factory + this.request = request; + this.externalType = type; + this.userRequest = userRequest; + this.external = true; + } + + libIdent() { + return this.userRequest; + } + + chunkCondition(chunk) { + return chunk.hasEntryModule(); + } + + identifier() { + return "external " + JSON.stringify(this.request); + } + + readableIdentifier() { + return "external " + JSON.stringify(this.request); + } + + needRebuild() { + return false; + } + + build(options, compilation, resolver, fs, callback) { + this.built = true; + this.buildMeta = {}; + this.buildInfo = {}; + callback(); + } + + 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 `(function() { module.exports = ${type}${objectLookup}; }());`; + } + + getSourceForCommonJsExternal(moduleAndSpecifiers) { + if (!Array.isArray(moduleAndSpecifiers)) { + return `module.exports = require(${JSON.stringify( + moduleAndSpecifiers + )});`; + } + + const moduleName = moduleAndSpecifiers[0]; + const objectLookup = moduleAndSpecifiers + .slice(1) + .map(r => `[${JSON.stringify(r)}]`) + .join(""); + return `module.exports = require(${JSON.stringify( + moduleName + )})${objectLookup};`; + } + + checkExternalVariable(variableToCheck, request) { + return `if(typeof ${variableToCheck} === 'undefined') {${WebpackMissingModule.moduleCode( + request + )}}\n`; + } + + getSourceForAmdOrUmdExternal(id, optional, request) { + const externalVariable = `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier( + `${id}` + )}__`; + const missingModuleError = optional + ? this.checkExternalVariable(externalVariable, request) + : ""; + return `${missingModuleError}module.exports = ${externalVariable};`; + } + + getSourceForDefaultCase(optional, request) { + if (!Array.isArray(request)) { + // make it an array as the look up works the same basically + request = [request]; + } + + const variableName = request[0]; + const missingModuleError = optional + ? this.checkExternalVariable(variableName, request.join(".")) + : ""; + const objectLookup = request + .slice(1) + .map(r => `[${JSON.stringify(r)}]`) + .join(""); + return `${missingModuleError}module.exports = ${variableName}${objectLookup};`; + } + + getSourceString(runtime) { + const request = + typeof this.request === "object" && !Array.isArray(this.request) + ? this.request[this.externalType] + : this.request; + switch (this.externalType) { + case "this": + case "window": + case "self": + return this.getSourceForGlobalVariableExternal( + request, + this.externalType + ); + case "global": + return this.getSourceForGlobalVariableExternal( + runtime.outputOptions.globalObject, + this.externalType + ); + case "commonjs": + case "commonjs2": + return this.getSourceForCommonJsExternal(request); + case "amd": + case "umd": + case "umd2": + return this.getSourceForAmdOrUmdExternal( + this.id, + this.optional, + request + ); + default: + return this.getSourceForDefaultCase(this.optional, request); + } + } + + getSource(sourceString) { + if (this.useSourceMap) { + return new OriginalSource(sourceString, this.identifier()); + } + + return new RawSource(sourceString); + } + + source(dependencyTemplates, runtime) { + return this.getSource(this.getSourceString(runtime)); + } + + size() { + return 42; + } + + /** + * @param {Hash} hash the hash used to track dependencies + * @returns {void} + */ + updateHash(hash) { + hash.update(this.externalType); + hash.update(JSON.stringify(this.request)); + hash.update(JSON.stringify(Boolean(this.optional))); + super.updateHash(hash); + } +} + +module.exports = ExternalModule; diff --git a/node_modules/webpack/lib/ExternalModuleFactoryPlugin.js b/node_modules/webpack/lib/ExternalModuleFactoryPlugin.js index 7066aae42..b75cc7476 100644 --- a/node_modules/webpack/lib/ExternalModuleFactoryPlugin.js +++ b/node_modules/webpack/lib/ExternalModuleFactoryPlugin.js @@ -1,91 +1,110 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const ExternalModule = require("./ExternalModule");
-
-class ExternalModuleFactoryPlugin {
- constructor(type, externals) {
- this.type = type;
- this.externals = externals;
- }
-
- apply(normalModuleFactory) {
- const globalType = this.type;
- normalModuleFactory.plugin("factory", factory => (data, callback) => {
- const context = data.context;
- const dependency = data.dependencies[0];
-
- function handleExternal(value, type, callback) {
- if(typeof type === "function") {
- callback = type;
- type = undefined;
- }
- if(value === false) return factory(data, callback);
- if(value === true) value = dependency.request;
- if(typeof type === "undefined" && /^[a-z0-9]+ /.test(value)) {
- const idx = value.indexOf(" ");
- type = value.substr(0, idx);
- value = value.substr(idx + 1);
- }
- callback(null, new ExternalModule(value, type || globalType, dependency.request));
- return true;
- }
- (function handleExternals(externals, callback) {
- if(typeof externals === "string") {
- if(externals === dependency.request) {
- return handleExternal(dependency.request, callback);
- }
- } else if(Array.isArray(externals)) {
- let i = 0;
- (function next() {
- let asyncFlag;
- const handleExternalsAndCallback = function 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); // eslint-disable-line keyword-spacing
- asyncFlag = false;
- }());
- return;
- } else if(externals instanceof RegExp) {
- if(externals.test(dependency.request)) {
- return handleExternal(dependency.request, callback);
- }
- } else if(typeof externals === "function") {
- externals.call(null, context, dependency.request, function(err, value, type) {
- if(err) return callback(err);
- if(typeof value !== "undefined") {
- handleExternal(value, type, callback);
- } else {
- callback();
- }
- });
- return;
- } else if(typeof externals === "object" && Object.prototype.hasOwnProperty.call(externals, dependency.request)) {
- return handleExternal(externals[dependency.request], callback);
- }
- callback();
- }(this.externals, function(err, module) {
- if(err) return callback(err);
- if(!module) return handleExternal(false, callback);
- return callback(null, module);
- }));
- });
- }
-}
-module.exports = ExternalModuleFactoryPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const ExternalModule = require("./ExternalModule"); + +class ExternalModuleFactoryPlugin { + constructor(type, externals) { + this.type = type; + this.externals = externals; + } + + apply(normalModuleFactory) { + const globalType = this.type; + normalModuleFactory.hooks.factory.tap( + "ExternalModuleFactoryPlugin", + factory => (data, callback) => { + const context = data.context; + const dependency = data.dependencies[0]; + + const handleExternal = (value, type, callback) => { + if (typeof type === "function") { + callback = type; + type = undefined; + } + if (value === false) return factory(data, callback); + if (value === true) value = dependency.request; + if (type === undefined && /^[a-z0-9]+ /.test(value)) { + const idx = value.indexOf(" "); + type = value.substr(0, idx); + value = value.substr(idx + 1); + } + callback( + null, + new ExternalModule(value, type || globalType, dependency.request) + ); + return true; + }; + + const handleExternals = (externals, callback) => { + if (typeof externals === "string") { + if (externals === dependency.request) { + return handleExternal(dependency.request, callback); + } + } else if (Array.isArray(externals)) { + let i = 0; + const next = () => { + let asyncFlag; + 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, callback); + } + } else if (typeof externals === "function") { + externals.call( + null, + context, + dependency.request, + (err, value, type) => { + if (err) return callback(err); + if (value !== undefined) { + handleExternal(value, type, callback); + } else { + callback(); + } + } + ); + return; + } else if ( + typeof externals === "object" && + Object.prototype.hasOwnProperty.call(externals, dependency.request) + ) { + return handleExternal(externals[dependency.request], callback); + } + callback(); + }; + + handleExternals(this.externals, (err, module) => { + if (err) return callback(err); + if (!module) return handleExternal(false, callback); + return callback(null, module); + }); + } + ); + } +} +module.exports = ExternalModuleFactoryPlugin; diff --git a/node_modules/webpack/lib/ExternalsPlugin.js b/node_modules/webpack/lib/ExternalsPlugin.js index 24cc3ad3a..697f1aaa0 100644 --- a/node_modules/webpack/lib/ExternalsPlugin.js +++ b/node_modules/webpack/lib/ExternalsPlugin.js @@ -1,21 +1,23 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const ExternalModuleFactoryPlugin = require("./ExternalModuleFactoryPlugin");
-
-class ExternalsPlugin {
- constructor(type, externals) {
- this.type = type;
- this.externals = externals;
- }
- apply(compiler) {
- compiler.plugin("compile", (params) => {
- params.normalModuleFactory.apply(new ExternalModuleFactoryPlugin(this.type, this.externals));
- });
- }
-}
-
-module.exports = ExternalsPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const ExternalModuleFactoryPlugin = require("./ExternalModuleFactoryPlugin"); + +class ExternalsPlugin { + constructor(type, externals) { + this.type = type; + this.externals = externals; + } + apply(compiler) { + compiler.hooks.compile.tap("ExternalsPlugin", ({ normalModuleFactory }) => { + new ExternalModuleFactoryPlugin(this.type, this.externals).apply( + normalModuleFactory + ); + }); + } +} + +module.exports = ExternalsPlugin; diff --git a/node_modules/webpack/lib/FlagDependencyExportsPlugin.js b/node_modules/webpack/lib/FlagDependencyExportsPlugin.js index ff5e11255..0aafb0b4a 100644 --- a/node_modules/webpack/lib/FlagDependencyExportsPlugin.js +++ b/node_modules/webpack/lib/FlagDependencyExportsPlugin.js @@ -1,101 +1,146 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-class FlagDependencyExportsPlugin {
-
- apply(compiler) {
- compiler.plugin("compilation", (compilation) => {
- compilation.plugin("finish-modules", (modules) => {
- const dependencies = Object.create(null);
-
- let module;
- let moduleWithExports;
- let moduleProvidedExports;
- const queue = modules.filter((m) => !m.providedExports);
- for(let i = 0; i < queue.length; i++) {
- module = queue[i];
-
- if(module.providedExports !== true) {
- moduleWithExports = module.meta && module.meta.harmonyModule;
- moduleProvidedExports = Array.isArray(module.providedExports) ? new Set(module.providedExports) : new Set();
- processDependenciesBlock(module);
- if(!moduleWithExports) {
- module.providedExports = true;
- notifyDependencies();
- } else if(module.providedExports !== true) {
- module.providedExports = Array.from(moduleProvidedExports);
- }
- }
- }
-
- function processDependenciesBlock(depBlock) {
- depBlock.dependencies.forEach((dep) => processDependency(dep));
- depBlock.variables.forEach((variable) => {
- variable.dependencies.forEach((dep) => processDependency(dep));
- });
- depBlock.blocks.forEach(processDependenciesBlock);
- }
-
- function processDependency(dep) {
- const exportDesc = dep.getExports && dep.getExports();
- if(!exportDesc) return;
- moduleWithExports = true;
- const exports = exportDesc.exports;
- const exportDeps = exportDesc.dependencies;
- if(exportDeps) {
- exportDeps.forEach((dep) => {
- const depIdent = dep.identifier();
- // if this was not yet initialized
- // initialize it as an array containing the module and stop
- const array = dependencies[depIdent];
- if(!array) {
- dependencies[depIdent] = [module];
- return;
- }
-
- // check if this module is known
- // if not, add it to the dependencies for this identifier
- if(array.indexOf(module) < 0)
- array.push(module);
- });
- }
- let changed = false;
- if(module.providedExports !== true) {
- if(exports === true) {
- module.providedExports = true;
- changed = true;
- } else if(Array.isArray(exports)) {
- changed = addToSet(moduleProvidedExports, exports);
- }
- }
- if(changed) {
- notifyDependencies();
- }
- }
-
- function notifyDependencies() {
- const deps = dependencies[module.identifier()];
- if(deps) {
- deps.forEach((dep) => queue.push(dep));
- }
- }
- });
-
- function addToSet(a, b) {
- let changed = false;
- b.forEach((item) => {
- if(!a.has(item)) {
- a.add(item);
- changed = true;
- }
- });
- return changed;
- }
- });
- }
-}
-
-module.exports = FlagDependencyExportsPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Queue = require("./util/Queue"); + +const addToSet = (a, b) => { + let changed = false; + for (const item of b) { + if (!a.has(item)) { + a.add(item); + changed = true; + } + } + return changed; +}; + +class FlagDependencyExportsPlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "FlagDependencyExportsPlugin", + compilation => { + compilation.hooks.finishModules.tap( + "FlagDependencyExportsPlugin", + modules => { + const dependencies = new Map(); + + const queue = new Queue(); + + let module; + let moduleWithExports; + let moduleProvidedExports; + + const processDependenciesBlock = depBlock => { + for (const dep of depBlock.dependencies) { + if (processDependency(dep)) return true; + } + for (const variable of depBlock.variables) { + for (const dep of variable.dependencies) { + if (processDependency(dep)) return true; + } + } + for (const block of depBlock.blocks) { + if (processDependenciesBlock(block)) return true; + } + return false; + }; + + const processDependency = dep => { + const exportDesc = dep.getExports && dep.getExports(); + if (!exportDesc) return; + moduleWithExports = true; + const exports = exportDesc.exports; + // break early if it's only in the worst state + if (module.buildMeta.providedExports === true) { + return true; + } + // break if it should move to the worst state + if (exports === true) { + module.buildMeta.providedExports = true; + notifyDependencies(); + return true; + } + // merge in new exports + if (Array.isArray(exports)) { + if (addToSet(moduleProvidedExports, exports)) { + notifyDependencies(); + } + } + // store dependencies + const exportDeps = exportDesc.dependencies; + if (exportDeps) { + 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); + } + } + } + return false; + }; + + const notifyDependencies = () => { + const deps = dependencies.get(module); + if (deps !== undefined) { + for (const dep of deps) { + queue.enqueue(dep); + } + } + }; + + // Start with all modules without provided exports + for (const module of modules) { + if (!module.buildMeta.providedExports) { + queue.enqueue(module); + } + } + + while (queue.length > 0) { + module = queue.dequeue(); + + if (module.buildMeta.providedExports !== true) { + moduleWithExports = + module.buildMeta && module.buildMeta.exportsType; + moduleProvidedExports = Array.isArray( + module.buildMeta.providedExports + ) + ? new Set(module.buildMeta.providedExports) + : new Set(); + processDependenciesBlock(module); + if (!moduleWithExports) { + module.buildMeta.providedExports = true; + notifyDependencies(); + } else if (module.buildMeta.providedExports !== true) { + module.buildMeta.providedExports = Array.from( + moduleProvidedExports + ); + } + } + } + } + ); + const providedExportsCache = new WeakMap(); + compilation.hooks.rebuildModule.tap( + "FlagDependencyExportsPlugin", + module => { + providedExportsCache.set(module, module.buildMeta.providedExports); + } + ); + compilation.hooks.finishRebuildingModule.tap( + "FlagDependencyExportsPlugin", + module => { + module.buildMeta.providedExports = providedExportsCache.get(module); + } + ); + } + ); + } +} + +module.exports = FlagDependencyExportsPlugin; diff --git a/node_modules/webpack/lib/FlagDependencyUsagePlugin.js b/node_modules/webpack/lib/FlagDependencyUsagePlugin.js index 40e1769b1..85c221608 100644 --- a/node_modules/webpack/lib/FlagDependencyUsagePlugin.js +++ b/node_modules/webpack/lib/FlagDependencyUsagePlugin.js @@ -1,81 +1,116 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-class FlagDependencyUsagePlugin {
- apply(compiler) {
- compiler.plugin("compilation", compilation => {
- compilation.plugin("optimize-modules-advanced", modules => {
-
- modules.forEach(module => module.used = false);
-
- const queue = [];
- compilation.chunks.forEach(chunk => {
- if(chunk.entryModule) {
- processModule(chunk.entryModule, true);
- }
- });
-
- while(queue.length) {
- const queueItem = queue.pop();
- processDependenciesBlock(queueItem[0], queueItem[1]);
- }
-
- function processModule(module, usedExports) {
- module.used = true;
- if(module.usedExports === true)
- return;
- else if(usedExports === true)
- module.usedExports = true;
- else if(Array.isArray(usedExports)) {
- const old = module.usedExports ? module.usedExports.length : -1;
- module.usedExports = addToSet(module.usedExports || [], usedExports);
- if(module.usedExports.length === old)
- return;
- } else if(Array.isArray(module.usedExports))
- return;
- else
- module.usedExports = false;
-
- queue.push([module, module.usedExports]);
- }
-
- function processDependenciesBlock(depBlock, usedExports) {
- depBlock.dependencies.forEach(dep => processDependency(dep));
- depBlock.variables.forEach(variable => variable.dependencies.forEach(dep => processDependency(dep)));
- depBlock.blocks.forEach(block => queue.push([block, usedExports]));
- }
-
- function processDependency(dep) {
- const reference = dep.getReference && dep.getReference();
- if(!reference) return;
- const module = reference.module;
- const importedNames = reference.importedNames;
- const oldUsed = module.used;
- const oldUsedExports = module.usedExports;
- if(!oldUsed || (importedNames && (!oldUsedExports || !isSubset(oldUsedExports, importedNames)))) {
- processModule(module, importedNames);
- }
- }
-
- });
-
- function addToSet(a, b) {
- b.forEach(item => {
- if(a.indexOf(item) < 0)
- a.push(item);
- });
- return a;
- }
-
- function isSubset(biggerSet, subset) {
- if(biggerSet === true) return true;
- if(subset === true) return false;
- return subset.every(item => biggerSet.indexOf(item) >= 0);
- }
- });
- }
-}
-module.exports = FlagDependencyUsagePlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ + +/** @typedef {false | true | string[]} UsedExports */ + +const addToSet = (a, b) => { + for (const item of b) { + if (!a.includes(item)) a.push(item); + } + return a; +}; + +const isSubset = (biggerSet, subset) => { + if (biggerSet === true) return true; + if (subset === true) return false; + return subset.every(item => biggerSet.indexOf(item) >= 0); +}; + +class FlagDependencyUsagePlugin { + apply(compiler) { + compiler.hooks.compilation.tap("FlagDependencyUsagePlugin", compilation => { + compilation.hooks.optimizeDependencies.tap( + "FlagDependencyUsagePlugin", + modules => { + const processModule = (module, usedExports) => { + module.used = true; + if (module.usedExports === true) return; + if (usedExports === true) { + module.usedExports = true; + } else if (Array.isArray(usedExports)) { + const old = module.usedExports ? module.usedExports.length : -1; + module.usedExports = addToSet( + module.usedExports || [], + usedExports + ); + if (module.usedExports.length === old) { + return; + } + } else if (Array.isArray(module.usedExports)) { + return; + } else { + module.usedExports = false; + } + + // 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 + if (module.factoryMeta.sideEffectFree) { + if (module.usedExports === false) return; + if ( + Array.isArray(module.usedExports) && + module.usedExports.length === 0 + ) + return; + } + + queue.push([module, module, module.usedExports]); + }; + + const processDependenciesBlock = (module, depBlock, usedExports) => { + for (const dep of depBlock.dependencies) { + processDependency(module, dep); + } + for (const variable of depBlock.variables) { + for (const dep of variable.dependencies) { + processDependency(module, dep); + } + } + for (const block of depBlock.blocks) { + queue.push([module, block, usedExports]); + } + }; + + const processDependency = (module, dep) => { + const reference = compilation.getDependencyReference(module, dep); + if (!reference) return; + const referenceModule = reference.module; + const importedNames = reference.importedNames; + const oldUsed = referenceModule.used; + const oldUsedExports = referenceModule.usedExports; + if ( + !oldUsed || + (importedNames && + (!oldUsedExports || !isSubset(oldUsedExports, importedNames))) + ) { + processModule(referenceModule, importedNames); + } + }; + + for (const module of modules) { + module.used = false; + } + + /** @type {[Module, DependenciesBlock, UsedExports][]} */ + const queue = []; + for (const preparedEntrypoint of compilation._preparedEntrypoints) { + if (preparedEntrypoint.module) { + processModule(preparedEntrypoint.module, true); + } + } + + while (queue.length) { + const queueItem = queue.pop(); + processDependenciesBlock(queueItem[0], queueItem[1], queueItem[2]); + } + } + ); + }); + } +} +module.exports = FlagDependencyUsagePlugin; diff --git a/node_modules/webpack/lib/FlagInitialModulesAsUsedPlugin.js b/node_modules/webpack/lib/FlagInitialModulesAsUsedPlugin.js index 0356006ab..7272ddb3a 100644 --- a/node_modules/webpack/lib/FlagInitialModulesAsUsedPlugin.js +++ b/node_modules/webpack/lib/FlagInitialModulesAsUsedPlugin.js @@ -1,24 +1,36 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-class FlagInitialModulesAsUsedPlugin {
- apply(compiler) {
- compiler.plugin("compilation", (compilation) => {
- compilation.plugin("after-optimize-chunks", (chunks) => {
- chunks.forEach((chunk) => {
- if(!chunk.isInitial()) {
- return;
- }
- chunk.forEachModule((module) => {
- module.usedExports = true;
- });
- });
- });
- });
- }
-}
-
-module.exports = FlagInitialModulesAsUsedPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +class FlagInitialModulesAsUsedPlugin { + constructor(explanation) { + this.explanation = explanation; + } + + apply(compiler) { + compiler.hooks.compilation.tap( + "FlagInitialModulesAsUsedPlugin", + compilation => { + compilation.hooks.afterOptimizeChunks.tap( + "FlagInitialModulesAsUsedPlugin", + chunks => { + for (const chunk of chunks) { + if (!chunk.isOnlyInitial()) { + return; + } + for (const module of chunk.modulesIterable) { + module.used = true; + module.usedExports = true; + module.addReason(null, null, this.explanation); + } + } + } + ); + } + ); + } +} + +module.exports = FlagInitialModulesAsUsedPlugin; diff --git a/node_modules/webpack/lib/FunctionModulePlugin.js b/node_modules/webpack/lib/FunctionModulePlugin.js index a150a94e3..fc4b2707f 100644 --- a/node_modules/webpack/lib/FunctionModulePlugin.js +++ b/node_modules/webpack/lib/FunctionModulePlugin.js @@ -1,24 +1,19 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const FunctionModuleTemplatePlugin = require("./FunctionModuleTemplatePlugin");
-const RequestShortener = require("./RequestShortener");
-
-class FunctionModulePlugin {
- constructor(options, requestShortener) {
- this.options = options;
- this.requestShortener = requestShortener;
- }
-
- apply(compiler) {
- compiler.plugin("compilation", (compilation) => {
- compilation.moduleTemplate.requestShortener = this.requestShortener || new RequestShortener(compiler.context);
- compilation.moduleTemplate.apply(new FunctionModuleTemplatePlugin());
- });
- }
-}
-
-module.exports = FunctionModulePlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const FunctionModuleTemplatePlugin = require("./FunctionModuleTemplatePlugin"); + +class FunctionModulePlugin { + apply(compiler) { + compiler.hooks.compilation.tap("FunctionModulePlugin", compilation => { + new FunctionModuleTemplatePlugin().apply( + compilation.moduleTemplates.javascript + ); + }); + } +} + +module.exports = FunctionModulePlugin; diff --git a/node_modules/webpack/lib/FunctionModuleTemplatePlugin.js b/node_modules/webpack/lib/FunctionModuleTemplatePlugin.js index 234a840f5..cf2e1b0ea 100644 --- a/node_modules/webpack/lib/FunctionModuleTemplatePlugin.js +++ b/node_modules/webpack/lib/FunctionModuleTemplatePlugin.js @@ -1,61 +1,100 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const ConcatSource = require("webpack-sources").ConcatSource;
-
-class FunctionModuleTemplatePlugin {
- apply(moduleTemplate) {
- moduleTemplate.plugin("render", function(moduleSource, module) {
- const source = new ConcatSource();
- const defaultArguments = [module.moduleArgument || "module", module.exportsArgument || "exports"];
- if((module.arguments && module.arguments.length !== 0) || module.hasDependencies(d => d.requireWebpackRequire !== false)) {
- defaultArguments.push("__webpack_require__");
- }
- source.add("/***/ (function(" + defaultArguments.concat(module.arguments || []).join(", ") + ") {\n\n");
- if(module.strict) source.add("\"use strict\";\n");
- source.add(moduleSource);
- source.add("\n\n/***/ })");
- return source;
- });
-
- moduleTemplate.plugin("package", function(moduleSource, module) {
- if(this.outputOptions.pathinfo) {
- const source = new ConcatSource();
- const req = module.readableIdentifier(this.requestShortener);
- source.add("/*!****" + req.replace(/./g, "*") + "****!*\\\n");
- source.add(" !*** " + req.replace(/\*\//g, "*_/") + " ***!\n");
- source.add(" \\****" + req.replace(/./g, "*") + "****/\n");
- if(Array.isArray(module.providedExports) && module.providedExports.length === 0)
- source.add("/*! no exports provided */\n");
- else if(Array.isArray(module.providedExports))
- source.add("/*! exports provided: " + module.providedExports.join(", ") + " */\n");
- else if(module.providedExports)
- source.add("/*! dynamic exports provided */\n");
- if(Array.isArray(module.usedExports) && module.usedExports.length === 0)
- source.add("/*! no exports used */\n");
- else if(Array.isArray(module.usedExports))
- source.add("/*! exports used: " + module.usedExports.join(", ") + " */\n");
- else if(module.usedExports)
- source.add("/*! all exports used */\n");
- if(module.optimizationBailout) {
- module.optimizationBailout.forEach(text => {
- if(typeof text === "function") text = text(this.requestShortener);
- source.add(`/*! ${text} */\n`);
- });
- }
- source.add(moduleSource);
- return source;
- }
- return moduleSource;
- });
-
- moduleTemplate.plugin("hash", function(hash) {
- hash.update("FunctionModuleTemplatePlugin");
- hash.update("2");
- });
- }
-}
-module.exports = FunctionModuleTemplatePlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const { ConcatSource } = require("webpack-sources"); +const Template = require("./Template"); + +class FunctionModuleTemplatePlugin { + apply(moduleTemplate) { + moduleTemplate.hooks.render.tap( + "FunctionModuleTemplatePlugin", + (moduleSource, module) => { + const source = new ConcatSource(); + const args = [module.moduleArgument]; + // TODO remove HACK checking type for javascript + if (module.type && module.type.startsWith("javascript")) { + args.push(module.exportsArgument); + if (module.hasDependencies(d => d.requireWebpackRequire !== false)) { + args.push("__webpack_require__"); + } + } else if (module.type && module.type.startsWith("json")) { + // no additional arguments needed + } else { + args.push(module.exportsArgument, "__webpack_require__"); + } + source.add("/***/ (function(" + args.join(", ") + ") {\n\n"); + if (module.buildInfo.strict) source.add('"use strict";\n'); + source.add(moduleSource); + source.add("\n\n/***/ })"); + return source; + } + ); + + moduleTemplate.hooks.package.tap( + "FunctionModuleTemplatePlugin", + (moduleSource, module) => { + if (moduleTemplate.runtimeTemplate.outputOptions.pathinfo) { + const source = new ConcatSource(); + const req = module.readableIdentifier( + moduleTemplate.runtimeTemplate.requestShortener + ); + source.add("/*!****" + req.replace(/./g, "*") + "****!*\\\n"); + source.add(" !*** " + req.replace(/\*\//g, "*_/") + " ***!\n"); + source.add(" \\****" + req.replace(/./g, "*") + "****/\n"); + if ( + Array.isArray(module.buildMeta.providedExports) && + module.buildMeta.providedExports.length === 0 + ) { + source.add(Template.toComment("no exports provided") + "\n"); + } else if (Array.isArray(module.buildMeta.providedExports)) { + source.add( + Template.toComment( + "exports provided: " + + module.buildMeta.providedExports.join(", ") + ) + "\n" + ); + } else if (module.buildMeta.providedExports) { + source.add(Template.toComment("no static exports found") + "\n"); + } + if ( + Array.isArray(module.usedExports) && + module.usedExports.length === 0 + ) { + source.add(Template.toComment("no exports used") + "\n"); + } else if (Array.isArray(module.usedExports)) { + source.add( + Template.toComment( + "exports used: " + module.usedExports.join(", ") + ) + "\n" + ); + } else if (module.usedExports) { + source.add(Template.toComment("all exports used") + "\n"); + } + if (module.optimizationBailout) { + for (const text of module.optimizationBailout) { + let code; + if (typeof text === "function") { + code = text(moduleTemplate.runtimeTemplate.requestShortener); + } else { + code = text; + } + source.add(Template.toComment(`${code}`) + "\n"); + } + } + source.add(moduleSource); + return source; + } + return moduleSource; + } + ); + + moduleTemplate.hooks.hash.tap("FunctionModuleTemplatePlugin", hash => { + hash.update("FunctionModuleTemplatePlugin"); + hash.update("2"); + }); + } +} +module.exports = FunctionModuleTemplatePlugin; diff --git a/node_modules/webpack/lib/HashedModuleIdsPlugin.js b/node_modules/webpack/lib/HashedModuleIdsPlugin.js index 40a491b07..aeb9f1d93 100644 --- a/node_modules/webpack/lib/HashedModuleIdsPlugin.js +++ b/node_modules/webpack/lib/HashedModuleIdsPlugin.js @@ -1,42 +1,53 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const createHash = require("crypto").createHash;
-
-class HashedModuleIdsPlugin {
- constructor(options) {
- this.options = Object.assign({
- hashFunction: "md5",
- hashDigest: "base64",
- hashDigestLength: 4
- }, options);
- }
-
- apply(compiler) {
- const options = this.options;
- compiler.plugin("compilation", (compilation) => {
- const usedIds = new Set();
- compilation.plugin("before-module-ids", (modules) => {
- modules.forEach((module) => {
- if(module.id === null && module.libIdent) {
- const id = module.libIdent({
- context: this.options.context || compiler.options.context
- });
- const hash = createHash(options.hashFunction);
- hash.update(id);
- const hashId = hash.digest(options.hashDigest);
- let len = options.hashDigestLength;
- while(usedIds.has(hashId.substr(0, len)))
- len++;
- module.id = hashId.substr(0, len);
- usedIds.add(module.id);
- }
- });
- });
- });
- }
-}
-
-module.exports = HashedModuleIdsPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const createHash = require("./util/createHash"); + +const validateOptions = require("schema-utils"); +const schema = require("../schemas/plugins/HashedModuleIdsPlugin.json"); + +class HashedModuleIdsPlugin { + constructor(options) { + validateOptions(schema, options || {}, "Hashed Module Ids Plugin"); + + this.options = Object.assign( + { + context: null, + hashFunction: "md4", + hashDigest: "base64", + hashDigestLength: 4 + }, + options + ); + } + + apply(compiler) { + const options = this.options; + compiler.hooks.compilation.tap("HashedModuleIdsPlugin", compilation => { + const usedIds = new Set(); + compilation.hooks.beforeModuleIds.tap( + "HashedModuleIdsPlugin", + modules => { + for (const module of modules) { + if (module.id === null && module.libIdent) { + const id = module.libIdent({ + context: this.options.context || compiler.options.context + }); + const hash = createHash(options.hashFunction); + hash.update(id); + const hashId = hash.digest(options.hashDigest); + let len = options.hashDigestLength; + while (usedIds.has(hashId.substr(0, len))) len++; + module.id = hashId.substr(0, len); + usedIds.add(module.id); + } + } + } + ); + }); + } +} + +module.exports = HashedModuleIdsPlugin; diff --git a/node_modules/webpack/lib/HotModuleReplacement.runtime.js b/node_modules/webpack/lib/HotModuleReplacement.runtime.js index 6db89aa2d..5497091c8 100644 --- a/node_modules/webpack/lib/HotModuleReplacement.runtime.js +++ b/node_modules/webpack/lib/HotModuleReplacement.runtime.js @@ -1,602 +1,645 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-/*global $hash$ $requestTimeout$ installedModules $require$ hotDownloadManifest hotDownloadUpdateChunk hotDisposeChunk modules */
-module.exports = function() {
-
- var hotApplyOnUpdate = true;
- var hotCurrentHash = $hash$; // eslint-disable-line no-unused-vars
- var hotRequestTimeout = $requestTimeout$;
- var hotCurrentModuleData = {};
- var hotCurrentChildModule; // eslint-disable-line no-unused-vars
- var hotCurrentParents = []; // eslint-disable-line no-unused-vars
- var hotCurrentParentsTemp = []; // eslint-disable-line no-unused-vars
-
- function hotCreateRequire(moduleId) { // eslint-disable-line no-unused-vars
- var me = installedModules[moduleId];
- if(!me) return $require$;
- var fn = function(request) {
- if(me.hot.active) {
- if(installedModules[request]) {
- if(installedModules[request].parents.indexOf(moduleId) < 0)
- installedModules[request].parents.push(moduleId);
- } else {
- hotCurrentParents = [moduleId];
- hotCurrentChildModule = request;
- }
- if(me.children.indexOf(request) < 0)
- me.children.push(request);
- } else {
- console.warn("[HMR] unexpected require(" + request + ") from disposed module " + moduleId);
- hotCurrentParents = [];
- }
- return $require$(request);
- };
- var ObjectFactory = function ObjectFactory(name) {
- return {
- configurable: true,
- enumerable: true,
- get: function() {
- return $require$[name];
- },
- set: function(value) {
- $require$[name] = value;
- }
- };
- };
- for(var name in $require$) {
- if(Object.prototype.hasOwnProperty.call($require$, name) && name !== "e") {
- Object.defineProperty(fn, name, ObjectFactory(name));
- }
- }
- fn.e = function(chunkId) {
- if(hotStatus === "ready")
- hotSetStatus("prepare");
- hotChunksLoading++;
- return $require$.e(chunkId).then(finishChunkLoading, function(err) {
- finishChunkLoading();
- throw err;
- });
-
- function finishChunkLoading() {
- hotChunksLoading--;
- if(hotStatus === "prepare") {
- if(!hotWaitingFilesMap[chunkId]) {
- hotEnsureUpdateChunk(chunkId);
- }
- if(hotChunksLoading === 0 && hotWaitingFiles === 0) {
- hotUpdateDownloaded();
- }
- }
- }
- };
- return fn;
- }
-
- function hotCreateModule(moduleId) { // eslint-disable-line no-unused-vars
- var hot = {
- // private stuff
- _acceptedDependencies: {},
- _declinedDependencies: {},
- _selfAccepted: false,
- _selfDeclined: false,
- _disposeHandlers: [],
- _main: hotCurrentChildModule !== moduleId,
-
- // Module API
- active: true,
- accept: function(dep, callback) {
- if(typeof dep === "undefined")
- hot._selfAccepted = true;
- else if(typeof dep === "function")
- hot._selfAccepted = dep;
- else if(typeof dep === "object")
- for(var i = 0; i < dep.length; i++)
- hot._acceptedDependencies[dep[i]] = callback || function() {};
- else
- hot._acceptedDependencies[dep] = callback || function() {};
- },
- decline: function(dep) {
- if(typeof dep === "undefined")
- hot._selfDeclined = true;
- else if(typeof dep === "object")
- for(var i = 0; i < dep.length; i++)
- hot._declinedDependencies[dep[i]] = true;
- else
- hot._declinedDependencies[dep] = true;
- },
- dispose: function(callback) {
- hot._disposeHandlers.push(callback);
- },
- addDisposeHandler: function(callback) {
- hot._disposeHandlers.push(callback);
- },
- removeDisposeHandler: function(callback) {
- var idx = hot._disposeHandlers.indexOf(callback);
- if(idx >= 0) hot._disposeHandlers.splice(idx, 1);
- },
-
- // Management API
- check: hotCheck,
- apply: hotApply,
- status: function(l) {
- if(!l) return hotStatus;
- hotStatusHandlers.push(l);
- },
- addStatusHandler: function(l) {
- hotStatusHandlers.push(l);
- },
- removeStatusHandler: function(l) {
- var idx = hotStatusHandlers.indexOf(l);
- if(idx >= 0) hotStatusHandlers.splice(idx, 1);
- },
-
- //inherit from previous dispose call
- data: hotCurrentModuleData[moduleId]
- };
- hotCurrentChildModule = undefined;
- return hot;
- }
-
- var hotStatusHandlers = [];
- var hotStatus = "idle";
-
- function hotSetStatus(newStatus) {
- hotStatus = newStatus;
- for(var i = 0; i < hotStatusHandlers.length; i++)
- hotStatusHandlers[i].call(null, newStatus);
- }
-
- // while downloading
- var hotWaitingFiles = 0;
- var hotChunksLoading = 0;
- var hotWaitingFilesMap = {};
- var hotRequestedFilesMap = {};
- var hotAvailableFilesMap = {};
- var hotDeferred;
-
- // The update info
- var hotUpdate, hotUpdateNewHash;
-
- function toModuleId(id) {
- var isNumber = (+id) + "" === id;
- return isNumber ? +id : id;
- }
-
- function hotCheck(apply) {
- if(hotStatus !== "idle") throw new Error("check() is only allowed in idle status");
- hotApplyOnUpdate = apply;
- hotSetStatus("check");
- return hotDownloadManifest(hotRequestTimeout).then(function(update) {
- if(!update) {
- hotSetStatus("idle");
- return null;
- }
- hotRequestedFilesMap = {};
- hotWaitingFilesMap = {};
- hotAvailableFilesMap = update.c;
- hotUpdateNewHash = update.h;
-
- hotSetStatus("prepare");
- var promise = new Promise(function(resolve, reject) {
- hotDeferred = {
- resolve: resolve,
- reject: reject
- };
- });
- hotUpdate = {};
- /*foreachInstalledChunks*/
- { // eslint-disable-line no-lone-blocks
- /*globals chunkId */
- hotEnsureUpdateChunk(chunkId);
- }
- if(hotStatus === "prepare" && hotChunksLoading === 0 && hotWaitingFiles === 0) {
- hotUpdateDownloaded();
- }
- return promise;
- });
- }
-
- function hotAddUpdateChunk(chunkId, moreModules) { // eslint-disable-line no-unused-vars
- if(!hotAvailableFilesMap[chunkId] || !hotRequestedFilesMap[chunkId])
- return;
- hotRequestedFilesMap[chunkId] = false;
- for(var moduleId in moreModules) {
- if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {
- hotUpdate[moduleId] = moreModules[moduleId];
- }
- }
- if(--hotWaitingFiles === 0 && hotChunksLoading === 0) {
- hotUpdateDownloaded();
- }
- }
-
- function hotEnsureUpdateChunk(chunkId) {
- if(!hotAvailableFilesMap[chunkId]) {
- hotWaitingFilesMap[chunkId] = true;
- } else {
- hotRequestedFilesMap[chunkId] = true;
- hotWaitingFiles++;
- hotDownloadUpdateChunk(chunkId);
- }
- }
-
- function hotUpdateDownloaded() {
- hotSetStatus("ready");
- var deferred = hotDeferred;
- hotDeferred = null;
- if(!deferred) return;
- if(hotApplyOnUpdate) {
- // Wrap deferred object in Promise to mark it as a well-handled Promise to
- // avoid triggering uncaught exception warning in Chrome.
- // See https://bugs.chromium.org/p/chromium/issues/detail?id=465666
- Promise.resolve().then(function() {
- return hotApply(hotApplyOnUpdate);
- }).then(
- function(result) {
- deferred.resolve(result);
- },
- function(err) {
- deferred.reject(err);
- }
- );
- } else {
- var outdatedModules = [];
- for(var id in hotUpdate) {
- if(Object.prototype.hasOwnProperty.call(hotUpdate, id)) {
- outdatedModules.push(toModuleId(id));
- }
- }
- deferred.resolve(outdatedModules);
- }
- }
-
- function hotApply(options) {
- if(hotStatus !== "ready") throw new Error("apply() is only allowed in ready status");
- options = options || {};
-
- var cb;
- var i;
- var j;
- var module;
- var moduleId;
-
- function getAffectedStuff(updateModuleId) {
- var outdatedModules = [updateModuleId];
- var outdatedDependencies = {};
-
- var queue = outdatedModules.slice().map(function(id) {
- return {
- chain: [id],
- id: id
- };
- });
- while(queue.length > 0) {
- var queueItem = queue.pop();
- var moduleId = queueItem.id;
- var chain = queueItem.chain;
- module = installedModules[moduleId];
- if(!module || module.hot._selfAccepted)
- continue;
- if(module.hot._selfDeclined) {
- return {
- type: "self-declined",
- chain: chain,
- moduleId: moduleId
- };
- }
- if(module.hot._main) {
- return {
- type: "unaccepted",
- chain: chain,
- moduleId: moduleId
- };
- }
- for(var i = 0; i < module.parents.length; i++) {
- var parentId = module.parents[i];
- var parent = installedModules[parentId];
- if(!parent) continue;
- if(parent.hot._declinedDependencies[moduleId]) {
- return {
- type: "declined",
- chain: chain.concat([parentId]),
- moduleId: moduleId,
- parentId: parentId
- };
- }
- if(outdatedModules.indexOf(parentId) >= 0) continue;
- if(parent.hot._acceptedDependencies[moduleId]) {
- if(!outdatedDependencies[parentId])
- outdatedDependencies[parentId] = [];
- addAllToSet(outdatedDependencies[parentId], [moduleId]);
- continue;
- }
- delete outdatedDependencies[parentId];
- outdatedModules.push(parentId);
- queue.push({
- chain: chain.concat([parentId]),
- id: parentId
- });
- }
- }
-
- return {
- type: "accepted",
- moduleId: updateModuleId,
- outdatedModules: outdatedModules,
- outdatedDependencies: outdatedDependencies
- };
- }
-
- function addAllToSet(a, b) {
- for(var i = 0; i < b.length; i++) {
- var item = b[i];
- if(a.indexOf(item) < 0)
- a.push(item);
- }
- }
-
- // at begin all updates modules are outdated
- // the "outdated" status can propagate to parents if they don't accept the children
- var outdatedDependencies = {};
- var outdatedModules = [];
- var appliedUpdate = {};
-
- var warnUnexpectedRequire = function warnUnexpectedRequire() {
- console.warn("[HMR] unexpected require(" + result.moduleId + ") to disposed module");
- };
-
- for(var id in hotUpdate) {
- if(Object.prototype.hasOwnProperty.call(hotUpdate, id)) {
- moduleId = toModuleId(id);
- var result;
- if(hotUpdate[id]) {
- result = getAffectedStuff(moduleId);
- } else {
- result = {
- type: "disposed",
- moduleId: id
- };
- }
- var abortError = false;
- var doApply = false;
- var doDispose = false;
- var chainInfo = "";
- if(result.chain) {
- chainInfo = "\nUpdate propagation: " + result.chain.join(" -> ");
- }
- switch(result.type) {
- case "self-declined":
- if(options.onDeclined)
- options.onDeclined(result);
- if(!options.ignoreDeclined)
- abortError = new Error("Aborted because of self decline: " + result.moduleId + chainInfo);
- break;
- case "declined":
- if(options.onDeclined)
- options.onDeclined(result);
- if(!options.ignoreDeclined)
- abortError = new Error("Aborted because of declined dependency: " + result.moduleId + " in " + result.parentId + chainInfo);
- break;
- case "unaccepted":
- if(options.onUnaccepted)
- options.onUnaccepted(result);
- if(!options.ignoreUnaccepted)
- abortError = new Error("Aborted because " + moduleId + " is not accepted" + chainInfo);
- break;
- case "accepted":
- if(options.onAccepted)
- options.onAccepted(result);
- doApply = true;
- break;
- case "disposed":
- if(options.onDisposed)
- options.onDisposed(result);
- doDispose = true;
- break;
- default:
- throw new Error("Unexception type " + result.type);
- }
- if(abortError) {
- hotSetStatus("abort");
- return Promise.reject(abortError);
- }
- if(doApply) {
- appliedUpdate[moduleId] = hotUpdate[moduleId];
- addAllToSet(outdatedModules, result.outdatedModules);
- for(moduleId in result.outdatedDependencies) {
- if(Object.prototype.hasOwnProperty.call(result.outdatedDependencies, moduleId)) {
- if(!outdatedDependencies[moduleId])
- outdatedDependencies[moduleId] = [];
- addAllToSet(outdatedDependencies[moduleId], result.outdatedDependencies[moduleId]);
- }
- }
- }
- if(doDispose) {
- addAllToSet(outdatedModules, [result.moduleId]);
- appliedUpdate[moduleId] = warnUnexpectedRequire;
- }
- }
- }
-
- // Store self accepted outdated modules to require them later by the module system
- var outdatedSelfAcceptedModules = [];
- for(i = 0; i < outdatedModules.length; i++) {
- moduleId = outdatedModules[i];
- if(installedModules[moduleId] && installedModules[moduleId].hot._selfAccepted)
- outdatedSelfAcceptedModules.push({
- module: moduleId,
- errorHandler: installedModules[moduleId].hot._selfAccepted
- });
- }
-
- // Now in "dispose" phase
- hotSetStatus("dispose");
- Object.keys(hotAvailableFilesMap).forEach(function(chunkId) {
- if(hotAvailableFilesMap[chunkId] === false) {
- hotDisposeChunk(chunkId);
- }
- });
-
- var idx;
- var queue = outdatedModules.slice();
- while(queue.length > 0) {
- moduleId = queue.pop();
- module = installedModules[moduleId];
- if(!module) continue;
-
- var data = {};
-
- // Call dispose handlers
- var disposeHandlers = module.hot._disposeHandlers;
- for(j = 0; j < disposeHandlers.length; j++) {
- cb = disposeHandlers[j];
- cb(data);
- }
- hotCurrentModuleData[moduleId] = data;
-
- // disable module (this disables requires from this module)
- module.hot.active = false;
-
- // remove module from cache
- delete installedModules[moduleId];
-
- // when disposing there is no need to call dispose handler
- delete outdatedDependencies[moduleId];
-
- // remove "parents" references from all children
- for(j = 0; j < module.children.length; j++) {
- var child = installedModules[module.children[j]];
- if(!child) continue;
- idx = child.parents.indexOf(moduleId);
- if(idx >= 0) {
- child.parents.splice(idx, 1);
- }
- }
- }
-
- // remove outdated dependency from module children
- var dependency;
- var moduleOutdatedDependencies;
- for(moduleId in outdatedDependencies) {
- if(Object.prototype.hasOwnProperty.call(outdatedDependencies, moduleId)) {
- module = installedModules[moduleId];
- if(module) {
- moduleOutdatedDependencies = outdatedDependencies[moduleId];
- for(j = 0; j < moduleOutdatedDependencies.length; j++) {
- dependency = moduleOutdatedDependencies[j];
- idx = module.children.indexOf(dependency);
- if(idx >= 0) module.children.splice(idx, 1);
- }
- }
- }
- }
-
- // Not in "apply" phase
- hotSetStatus("apply");
-
- hotCurrentHash = hotUpdateNewHash;
-
- // insert new code
- for(moduleId in appliedUpdate) {
- if(Object.prototype.hasOwnProperty.call(appliedUpdate, moduleId)) {
- modules[moduleId] = appliedUpdate[moduleId];
- }
- }
-
- // call accept handlers
- var error = null;
- for(moduleId in outdatedDependencies) {
- if(Object.prototype.hasOwnProperty.call(outdatedDependencies, moduleId)) {
- module = installedModules[moduleId];
- if(module) {
- moduleOutdatedDependencies = outdatedDependencies[moduleId];
- var callbacks = [];
- for(i = 0; i < moduleOutdatedDependencies.length; i++) {
- dependency = moduleOutdatedDependencies[i];
- cb = module.hot._acceptedDependencies[dependency];
- if(cb) {
- if(callbacks.indexOf(cb) >= 0) continue;
- callbacks.push(cb);
- }
- }
- for(i = 0; i < callbacks.length; i++) {
- cb = callbacks[i];
- try {
- cb(moduleOutdatedDependencies);
- } catch(err) {
- if(options.onErrored) {
- options.onErrored({
- type: "accept-errored",
- moduleId: moduleId,
- dependencyId: moduleOutdatedDependencies[i],
- error: err
- });
- }
- if(!options.ignoreErrored) {
- if(!error)
- error = err;
- }
- }
- }
- }
- }
- }
-
- // Load self accepted modules
- for(i = 0; i < outdatedSelfAcceptedModules.length; i++) {
- var item = outdatedSelfAcceptedModules[i];
- moduleId = item.module;
- hotCurrentParents = [moduleId];
- try {
- $require$(moduleId);
- } catch(err) {
- if(typeof item.errorHandler === "function") {
- try {
- item.errorHandler(err);
- } catch(err2) {
- if(options.onErrored) {
- options.onErrored({
- type: "self-accept-error-handler-errored",
- moduleId: moduleId,
- error: err2,
- orginalError: err, // TODO remove in webpack 4
- originalError: err
- });
- }
- if(!options.ignoreErrored) {
- if(!error)
- error = err2;
- }
- if(!error)
- error = err;
- }
- } else {
- if(options.onErrored) {
- options.onErrored({
- type: "self-accept-errored",
- moduleId: moduleId,
- error: err
- });
- }
- if(!options.ignoreErrored) {
- if(!error)
- error = err;
- }
- }
- }
- }
-
- // handle errors in accept handlers and self accepted module load
- if(error) {
- hotSetStatus("fail");
- return Promise.reject(error);
- }
-
- hotSetStatus("idle");
- return new Promise(function(resolve) {
- resolve(outdatedModules);
- });
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +/*global $hash$ $requestTimeout$ installedModules $require$ hotDownloadManifest hotDownloadUpdateChunk hotDisposeChunk modules */ +module.exports = function() { + var hotApplyOnUpdate = true; + // eslint-disable-next-line no-unused-vars + var hotCurrentHash = $hash$; + var hotRequestTimeout = $requestTimeout$; + var hotCurrentModuleData = {}; + var hotCurrentChildModule; + // eslint-disable-next-line no-unused-vars + var hotCurrentParents = []; + // eslint-disable-next-line no-unused-vars + var hotCurrentParentsTemp = []; + + // eslint-disable-next-line no-unused-vars + function hotCreateRequire(moduleId) { + var me = installedModules[moduleId]; + if (!me) return $require$; + var fn = function(request) { + if (me.hot.active) { + if (installedModules[request]) { + if (installedModules[request].parents.indexOf(moduleId) === -1) { + installedModules[request].parents.push(moduleId); + } + } else { + hotCurrentParents = [moduleId]; + hotCurrentChildModule = request; + } + if (me.children.indexOf(request) === -1) { + me.children.push(request); + } + } else { + console.warn( + "[HMR] unexpected require(" + + request + + ") from disposed module " + + moduleId + ); + hotCurrentParents = []; + } + return $require$(request); + }; + var ObjectFactory = function ObjectFactory(name) { + return { + configurable: true, + enumerable: true, + get: function() { + return $require$[name]; + }, + set: function(value) { + $require$[name] = value; + } + }; + }; + for (var name in $require$) { + if ( + Object.prototype.hasOwnProperty.call($require$, name) && + name !== "e" && + name !== "t" + ) { + Object.defineProperty(fn, name, ObjectFactory(name)); + } + } + fn.e = function(chunkId) { + if (hotStatus === "ready") hotSetStatus("prepare"); + hotChunksLoading++; + return $require$.e(chunkId).then(finishChunkLoading, function(err) { + finishChunkLoading(); + throw err; + }); + + function finishChunkLoading() { + hotChunksLoading--; + if (hotStatus === "prepare") { + if (!hotWaitingFilesMap[chunkId]) { + hotEnsureUpdateChunk(chunkId); + } + if (hotChunksLoading === 0 && hotWaitingFiles === 0) { + hotUpdateDownloaded(); + } + } + } + }; + fn.t = function(value, mode) { + if (mode & 1) value = fn(value); + return $require$.t(value, mode & ~1); + }; + return fn; + } + + // eslint-disable-next-line no-unused-vars + function hotCreateModule(moduleId) { + var hot = { + // private stuff + _acceptedDependencies: {}, + _declinedDependencies: {}, + _selfAccepted: false, + _selfDeclined: false, + _disposeHandlers: [], + _main: hotCurrentChildModule !== moduleId, + + // Module API + active: true, + accept: function(dep, callback) { + if (dep === undefined) hot._selfAccepted = true; + else if (typeof dep === "function") hot._selfAccepted = dep; + else if (typeof dep === "object") + for (var i = 0; i < dep.length; i++) + hot._acceptedDependencies[dep[i]] = callback || function() {}; + else hot._acceptedDependencies[dep] = callback || function() {}; + }, + decline: function(dep) { + if (dep === undefined) hot._selfDeclined = true; + else if (typeof dep === "object") + for (var i = 0; i < dep.length; i++) + hot._declinedDependencies[dep[i]] = true; + else hot._declinedDependencies[dep] = true; + }, + dispose: function(callback) { + hot._disposeHandlers.push(callback); + }, + addDisposeHandler: function(callback) { + hot._disposeHandlers.push(callback); + }, + removeDisposeHandler: function(callback) { + var idx = hot._disposeHandlers.indexOf(callback); + if (idx >= 0) hot._disposeHandlers.splice(idx, 1); + }, + + // Management API + check: hotCheck, + apply: hotApply, + status: function(l) { + if (!l) return hotStatus; + hotStatusHandlers.push(l); + }, + addStatusHandler: function(l) { + hotStatusHandlers.push(l); + }, + removeStatusHandler: function(l) { + var idx = hotStatusHandlers.indexOf(l); + if (idx >= 0) hotStatusHandlers.splice(idx, 1); + }, + + //inherit from previous dispose call + data: hotCurrentModuleData[moduleId] + }; + hotCurrentChildModule = undefined; + return hot; + } + + var hotStatusHandlers = []; + var hotStatus = "idle"; + + function hotSetStatus(newStatus) { + hotStatus = newStatus; + for (var i = 0; i < hotStatusHandlers.length; i++) + hotStatusHandlers[i].call(null, newStatus); + } + + // while downloading + var hotWaitingFiles = 0; + var hotChunksLoading = 0; + var hotWaitingFilesMap = {}; + var hotRequestedFilesMap = {}; + var hotAvailableFilesMap = {}; + var hotDeferred; + + // The update info + var hotUpdate, hotUpdateNewHash; + + function toModuleId(id) { + var isNumber = +id + "" === id; + return isNumber ? +id : id; + } + + function hotCheck(apply) { + if (hotStatus !== "idle") { + throw new Error("check() is only allowed in idle status"); + } + hotApplyOnUpdate = apply; + hotSetStatus("check"); + return hotDownloadManifest(hotRequestTimeout).then(function(update) { + if (!update) { + hotSetStatus("idle"); + return null; + } + hotRequestedFilesMap = {}; + hotWaitingFilesMap = {}; + hotAvailableFilesMap = update.c; + hotUpdateNewHash = update.h; + + hotSetStatus("prepare"); + var promise = new Promise(function(resolve, reject) { + hotDeferred = { + resolve: resolve, + reject: reject + }; + }); + hotUpdate = {}; + /*foreachInstalledChunks*/ + // eslint-disable-next-line no-lone-blocks + { + /*globals chunkId */ + hotEnsureUpdateChunk(chunkId); + } + if ( + hotStatus === "prepare" && + hotChunksLoading === 0 && + hotWaitingFiles === 0 + ) { + hotUpdateDownloaded(); + } + return promise; + }); + } + + // eslint-disable-next-line no-unused-vars + function hotAddUpdateChunk(chunkId, moreModules) { + if (!hotAvailableFilesMap[chunkId] || !hotRequestedFilesMap[chunkId]) + return; + hotRequestedFilesMap[chunkId] = false; + for (var moduleId in moreModules) { + if (Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { + hotUpdate[moduleId] = moreModules[moduleId]; + } + } + if (--hotWaitingFiles === 0 && hotChunksLoading === 0) { + hotUpdateDownloaded(); + } + } + + function hotEnsureUpdateChunk(chunkId) { + if (!hotAvailableFilesMap[chunkId]) { + hotWaitingFilesMap[chunkId] = true; + } else { + hotRequestedFilesMap[chunkId] = true; + hotWaitingFiles++; + hotDownloadUpdateChunk(chunkId); + } + } + + function hotUpdateDownloaded() { + hotSetStatus("ready"); + var deferred = hotDeferred; + hotDeferred = null; + if (!deferred) return; + if (hotApplyOnUpdate) { + // Wrap deferred object in Promise to mark it as a well-handled Promise to + // avoid triggering uncaught exception warning in Chrome. + // See https://bugs.chromium.org/p/chromium/issues/detail?id=465666 + Promise.resolve() + .then(function() { + return hotApply(hotApplyOnUpdate); + }) + .then( + function(result) { + deferred.resolve(result); + }, + function(err) { + deferred.reject(err); + } + ); + } else { + var outdatedModules = []; + for (var id in hotUpdate) { + if (Object.prototype.hasOwnProperty.call(hotUpdate, id)) { + outdatedModules.push(toModuleId(id)); + } + } + deferred.resolve(outdatedModules); + } + } + + function hotApply(options) { + if (hotStatus !== "ready") + throw new Error("apply() is only allowed in ready status"); + options = options || {}; + + var cb; + var i; + var j; + var module; + var moduleId; + + function getAffectedStuff(updateModuleId) { + var outdatedModules = [updateModuleId]; + var outdatedDependencies = {}; + + var queue = outdatedModules.slice().map(function(id) { + return { + chain: [id], + id: id + }; + }); + while (queue.length > 0) { + var queueItem = queue.pop(); + var moduleId = queueItem.id; + var chain = queueItem.chain; + module = installedModules[moduleId]; + if (!module || module.hot._selfAccepted) continue; + if (module.hot._selfDeclined) { + return { + type: "self-declined", + chain: chain, + moduleId: moduleId + }; + } + if (module.hot._main) { + return { + type: "unaccepted", + chain: chain, + moduleId: moduleId + }; + } + for (var i = 0; i < module.parents.length; i++) { + var parentId = module.parents[i]; + var parent = installedModules[parentId]; + if (!parent) continue; + if (parent.hot._declinedDependencies[moduleId]) { + return { + type: "declined", + chain: chain.concat([parentId]), + moduleId: moduleId, + parentId: parentId + }; + } + if (outdatedModules.indexOf(parentId) !== -1) continue; + if (parent.hot._acceptedDependencies[moduleId]) { + if (!outdatedDependencies[parentId]) + outdatedDependencies[parentId] = []; + addAllToSet(outdatedDependencies[parentId], [moduleId]); + continue; + } + delete outdatedDependencies[parentId]; + outdatedModules.push(parentId); + queue.push({ + chain: chain.concat([parentId]), + id: parentId + }); + } + } + + return { + type: "accepted", + moduleId: updateModuleId, + outdatedModules: outdatedModules, + outdatedDependencies: outdatedDependencies + }; + } + + function addAllToSet(a, b) { + for (var i = 0; i < b.length; i++) { + var item = b[i]; + if (a.indexOf(item) === -1) a.push(item); + } + } + + // at begin all updates modules are outdated + // the "outdated" status can propagate to parents if they don't accept the children + var outdatedDependencies = {}; + var outdatedModules = []; + var appliedUpdate = {}; + + var warnUnexpectedRequire = function warnUnexpectedRequire() { + console.warn( + "[HMR] unexpected require(" + result.moduleId + ") to disposed module" + ); + }; + + for (var id in hotUpdate) { + if (Object.prototype.hasOwnProperty.call(hotUpdate, id)) { + moduleId = toModuleId(id); + /** @type {TODO} */ + var result; + if (hotUpdate[id]) { + result = getAffectedStuff(moduleId); + } else { + result = { + type: "disposed", + moduleId: id + }; + } + /** @type {Error|false} */ + var abortError = false; + var doApply = false; + var doDispose = false; + var chainInfo = ""; + if (result.chain) { + chainInfo = "\nUpdate propagation: " + result.chain.join(" -> "); + } + switch (result.type) { + case "self-declined": + if (options.onDeclined) options.onDeclined(result); + if (!options.ignoreDeclined) + abortError = new Error( + "Aborted because of self decline: " + + result.moduleId + + chainInfo + ); + break; + case "declined": + if (options.onDeclined) options.onDeclined(result); + if (!options.ignoreDeclined) + abortError = new Error( + "Aborted because of declined dependency: " + + result.moduleId + + " in " + + result.parentId + + chainInfo + ); + break; + case "unaccepted": + if (options.onUnaccepted) options.onUnaccepted(result); + if (!options.ignoreUnaccepted) + abortError = new Error( + "Aborted because " + moduleId + " is not accepted" + chainInfo + ); + break; + case "accepted": + if (options.onAccepted) options.onAccepted(result); + doApply = true; + break; + case "disposed": + if (options.onDisposed) options.onDisposed(result); + doDispose = true; + break; + default: + throw new Error("Unexception type " + result.type); + } + if (abortError) { + hotSetStatus("abort"); + return Promise.reject(abortError); + } + if (doApply) { + appliedUpdate[moduleId] = hotUpdate[moduleId]; + addAllToSet(outdatedModules, result.outdatedModules); + for (moduleId in result.outdatedDependencies) { + if ( + Object.prototype.hasOwnProperty.call( + result.outdatedDependencies, + moduleId + ) + ) { + if (!outdatedDependencies[moduleId]) + outdatedDependencies[moduleId] = []; + addAllToSet( + outdatedDependencies[moduleId], + result.outdatedDependencies[moduleId] + ); + } + } + } + if (doDispose) { + addAllToSet(outdatedModules, [result.moduleId]); + appliedUpdate[moduleId] = warnUnexpectedRequire; + } + } + } + + // Store self accepted outdated modules to require them later by the module system + var outdatedSelfAcceptedModules = []; + for (i = 0; i < outdatedModules.length; i++) { + moduleId = outdatedModules[i]; + if ( + installedModules[moduleId] && + installedModules[moduleId].hot._selfAccepted + ) + outdatedSelfAcceptedModules.push({ + module: moduleId, + errorHandler: installedModules[moduleId].hot._selfAccepted + }); + } + + // Now in "dispose" phase + hotSetStatus("dispose"); + Object.keys(hotAvailableFilesMap).forEach(function(chunkId) { + if (hotAvailableFilesMap[chunkId] === false) { + hotDisposeChunk(chunkId); + } + }); + + var idx; + var queue = outdatedModules.slice(); + while (queue.length > 0) { + moduleId = queue.pop(); + module = installedModules[moduleId]; + if (!module) continue; + + var data = {}; + + // Call dispose handlers + var disposeHandlers = module.hot._disposeHandlers; + for (j = 0; j < disposeHandlers.length; j++) { + cb = disposeHandlers[j]; + cb(data); + } + hotCurrentModuleData[moduleId] = data; + + // disable module (this disables requires from this module) + module.hot.active = false; + + // remove module from cache + delete installedModules[moduleId]; + + // when disposing there is no need to call dispose handler + delete outdatedDependencies[moduleId]; + + // remove "parents" references from all children + for (j = 0; j < module.children.length; j++) { + var child = installedModules[module.children[j]]; + if (!child) continue; + idx = child.parents.indexOf(moduleId); + if (idx >= 0) { + child.parents.splice(idx, 1); + } + } + } + + // remove outdated dependency from module children + var dependency; + var moduleOutdatedDependencies; + for (moduleId in outdatedDependencies) { + if ( + Object.prototype.hasOwnProperty.call(outdatedDependencies, moduleId) + ) { + module = installedModules[moduleId]; + if (module) { + moduleOutdatedDependencies = outdatedDependencies[moduleId]; + for (j = 0; j < moduleOutdatedDependencies.length; j++) { + dependency = moduleOutdatedDependencies[j]; + idx = module.children.indexOf(dependency); + if (idx >= 0) module.children.splice(idx, 1); + } + } + } + } + + // Not in "apply" phase + hotSetStatus("apply"); + + hotCurrentHash = hotUpdateNewHash; + + // insert new code + for (moduleId in appliedUpdate) { + if (Object.prototype.hasOwnProperty.call(appliedUpdate, moduleId)) { + modules[moduleId] = appliedUpdate[moduleId]; + } + } + + // call accept handlers + var error = null; + for (moduleId in outdatedDependencies) { + if ( + Object.prototype.hasOwnProperty.call(outdatedDependencies, moduleId) + ) { + module = installedModules[moduleId]; + if (module) { + moduleOutdatedDependencies = outdatedDependencies[moduleId]; + var callbacks = []; + for (i = 0; i < moduleOutdatedDependencies.length; i++) { + dependency = moduleOutdatedDependencies[i]; + cb = module.hot._acceptedDependencies[dependency]; + if (cb) { + if (callbacks.indexOf(cb) !== -1) continue; + callbacks.push(cb); + } + } + for (i = 0; i < callbacks.length; i++) { + cb = callbacks[i]; + try { + cb(moduleOutdatedDependencies); + } catch (err) { + if (options.onErrored) { + options.onErrored({ + type: "accept-errored", + moduleId: moduleId, + dependencyId: moduleOutdatedDependencies[i], + error: err + }); + } + if (!options.ignoreErrored) { + if (!error) error = err; + } + } + } + } + } + } + + // Load self accepted modules + for (i = 0; i < outdatedSelfAcceptedModules.length; i++) { + var item = outdatedSelfAcceptedModules[i]; + moduleId = item.module; + hotCurrentParents = [moduleId]; + try { + $require$(moduleId); + } catch (err) { + if (typeof item.errorHandler === "function") { + try { + item.errorHandler(err); + } catch (err2) { + if (options.onErrored) { + options.onErrored({ + type: "self-accept-error-handler-errored", + moduleId: moduleId, + error: err2, + originalError: err + }); + } + if (!options.ignoreErrored) { + if (!error) error = err2; + } + if (!error) error = err; + } + } else { + if (options.onErrored) { + options.onErrored({ + type: "self-accept-errored", + moduleId: moduleId, + error: err + }); + } + if (!options.ignoreErrored) { + if (!error) error = err; + } + } + } + } + + // handle errors in accept handlers and self accepted module load + if (error) { + hotSetStatus("fail"); + return Promise.reject(error); + } + + hotSetStatus("idle"); + return new Promise(function(resolve) { + resolve(outdatedModules); + }); + } +}; diff --git a/node_modules/webpack/lib/HotModuleReplacementPlugin.js b/node_modules/webpack/lib/HotModuleReplacementPlugin.js index f3cc63b94..365a2443a 100644 --- a/node_modules/webpack/lib/HotModuleReplacementPlugin.js +++ b/node_modules/webpack/lib/HotModuleReplacementPlugin.js @@ -1,251 +1,407 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const Template = require("./Template");
-const ModuleHotAcceptDependency = require("./dependencies/ModuleHotAcceptDependency");
-const ModuleHotDeclineDependency = require("./dependencies/ModuleHotDeclineDependency");
-const RawSource = require("webpack-sources").RawSource;
-const ConstDependency = require("./dependencies/ConstDependency");
-const NullFactory = require("./NullFactory");
-const ParserHelpers = require("./ParserHelpers");
-
-module.exports = class HotModuleReplacementPlugin {
- constructor(options) {
- this.options = options || {};
- this.multiStep = this.options.multiStep;
- this.fullBuildTimeout = this.options.fullBuildTimeout || 200;
- this.requestTimeout = this.options.requestTimeout || 10000;
- }
-
- apply(compiler) {
- const multiStep = this.multiStep;
- const fullBuildTimeout = this.fullBuildTimeout;
- const requestTimeout = this.requestTimeout;
- const hotUpdateChunkFilename = compiler.options.output.hotUpdateChunkFilename;
- const hotUpdateMainFilename = compiler.options.output.hotUpdateMainFilename;
- compiler.plugin("additional-pass", callback => {
- if(multiStep)
- return setTimeout(callback, fullBuildTimeout);
- return callback();
- });
- compiler.plugin("compilation", (compilation, params) => {
- const hotUpdateChunkTemplate = compilation.hotUpdateChunkTemplate;
- if(!hotUpdateChunkTemplate) return;
-
- const normalModuleFactory = params.normalModuleFactory;
-
- compilation.dependencyFactories.set(ConstDependency, new NullFactory());
- compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
-
- compilation.dependencyFactories.set(ModuleHotAcceptDependency, normalModuleFactory);
- compilation.dependencyTemplates.set(ModuleHotAcceptDependency, new ModuleHotAcceptDependency.Template());
-
- compilation.dependencyFactories.set(ModuleHotDeclineDependency, normalModuleFactory);
- compilation.dependencyTemplates.set(ModuleHotDeclineDependency, new ModuleHotDeclineDependency.Template());
-
- compilation.plugin("record", function(compilation, records) {
- if(records.hash === this.hash) return;
- records.hash = compilation.hash;
- records.moduleHashs = {};
- this.modules.forEach(module => {
- const identifier = module.identifier();
- const hash = require("crypto").createHash("md5");
- module.updateHash(hash);
- records.moduleHashs[identifier] = hash.digest("hex");
- });
- records.chunkHashs = {};
- this.chunks.forEach(chunk => {
- records.chunkHashs[chunk.id] = chunk.hash;
- });
- records.chunkModuleIds = {};
- this.chunks.forEach(chunk => {
- records.chunkModuleIds[chunk.id] = chunk.mapModules(m => m.id);
- });
- });
- let initialPass = false;
- let recompilation = false;
- compilation.plugin("after-hash", function() {
- let records = this.records;
- if(!records) {
- initialPass = true;
- return;
- }
- if(!records.hash)
- initialPass = true;
- const preHash = records.preHash || "x";
- const prepreHash = records.prepreHash || "x";
- if(preHash === this.hash) {
- recompilation = true;
- this.modifyHash(prepreHash);
- return;
- }
- records.prepreHash = records.hash || "x";
- records.preHash = this.hash;
- this.modifyHash(records.prepreHash);
- });
- compilation.plugin("should-generate-chunk-assets", () => {
- if(multiStep && !recompilation && !initialPass)
- return false;
- });
- compilation.plugin("need-additional-pass", () => {
- if(multiStep && !recompilation && !initialPass)
- return true;
- });
- compilation.plugin("additional-chunk-assets", function() {
- const records = this.records;
- if(records.hash === this.hash) return;
- if(!records.moduleHashs || !records.chunkHashs || !records.chunkModuleIds) return;
- this.modules.forEach(module => {
- const identifier = module.identifier();
- let hash = require("crypto").createHash("md5");
- module.updateHash(hash);
- hash = hash.digest("hex");
- module.hotUpdate = records.moduleHashs[identifier] !== hash;
- });
- const hotUpdateMainContent = {
- h: this.hash,
- c: {},
- };
- Object.keys(records.chunkHashs).forEach(function(chunkId) {
- chunkId = isNaN(+chunkId) ? chunkId : +chunkId;
- const currentChunk = this.chunks.find(chunk => chunk.id === chunkId);
- if(currentChunk) {
- const newModules = currentChunk.getModules().filter(module => module.hotUpdate);
- const allModules = {};
- currentChunk.forEachModule(module => {
- allModules[module.id] = true;
- });
- const removedModules = records.chunkModuleIds[chunkId].filter(id => !allModules[id]);
- if(newModules.length > 0 || removedModules.length > 0) {
- const source = hotUpdateChunkTemplate.render(chunkId, newModules, removedModules, this.hash, this.moduleTemplate, this.dependencyTemplates);
- const filename = this.getPath(hotUpdateChunkFilename, {
- hash: records.hash,
- chunk: currentChunk
- });
- this.additionalChunkAssets.push(filename);
- this.assets[filename] = source;
- hotUpdateMainContent.c[chunkId] = true;
- currentChunk.files.push(filename);
- this.applyPlugins("chunk-asset", currentChunk, filename);
- }
- } else {
- hotUpdateMainContent.c[chunkId] = false;
- }
- }, this);
- const source = new RawSource(JSON.stringify(hotUpdateMainContent));
- const filename = this.getPath(hotUpdateMainFilename, {
- hash: records.hash
- });
- this.assets[filename] = source;
- });
-
- compilation.mainTemplate.plugin("hash", hash => {
- hash.update("HotMainTemplateDecorator");
- });
-
- compilation.mainTemplate.plugin("module-require", (_, chunk, hash, varModuleId) => {
- return `hotCreateRequire(${varModuleId})`;
- });
-
- compilation.mainTemplate.plugin("require-extensions", function(source) {
- const buf = [source];
- buf.push("");
- buf.push("// __webpack_hash__");
- buf.push(this.requireFn + ".h = function() { return hotCurrentHash; };");
- return this.asString(buf);
- });
-
- compilation.mainTemplate.plugin("bootstrap", function(source, chunk, hash) {
- source = this.applyPluginsWaterfall("hot-bootstrap", source, chunk, hash);
- return this.asString([
- source,
- "",
- hotInitCode
- .replace(/\$require\$/g, this.requireFn)
- .replace(/\$hash\$/g, JSON.stringify(hash))
- .replace(/\$requestTimeout\$/g, requestTimeout)
- .replace(/\/\*foreachInstalledChunks\*\//g, chunk.chunks.length > 0 ? "for(var chunkId in installedChunks)" : `var chunkId = ${JSON.stringify(chunk.id)};`)
- ]);
- });
-
- compilation.mainTemplate.plugin("global-hash", () => true);
-
- compilation.mainTemplate.plugin("current-hash", (_, length) => {
- if(isFinite(length))
- return `hotCurrentHash.substr(0, ${length})`;
- else
- return "hotCurrentHash";
- });
-
- compilation.mainTemplate.plugin("module-obj", function(source, chunk, hash, varModuleId) {
- return this.asString([
- `${source},`,
- `hot: hotCreateModule(${varModuleId}),`,
- "parents: (hotCurrentParentsTemp = hotCurrentParents, hotCurrentParents = [], hotCurrentParentsTemp),",
- "children: []"
- ]);
- });
-
- params.normalModuleFactory.plugin("parser", (parser, parserOptions) => {
- parser.plugin("expression __webpack_hash__", ParserHelpers.toConstantDependency("__webpack_require__.h()"));
- parser.plugin("evaluate typeof __webpack_hash__", ParserHelpers.evaluateToString("string"));
- parser.plugin("evaluate Identifier module.hot", function(expr) {
- return ParserHelpers.evaluateToIdentifier("module.hot", !!this.state.compilation.hotUpdateChunkTemplate)(expr);
- });
- parser.plugin("call module.hot.accept", function(expr) {
- if(!this.state.compilation.hotUpdateChunkTemplate) return false;
- if(expr.arguments.length >= 1) {
- const arg = this.evaluateExpression(expr.arguments[0]);
- let params = [];
- let requests = [];
- if(arg.isString()) {
- params = [arg];
- } else if(arg.isArray()) {
- params = arg.items.filter(param => param.isString());
- }
- if(params.length > 0) {
- params.forEach((param, idx) => {
- const request = param.string;
- const dep = new ModuleHotAcceptDependency(request, param.range);
- dep.optional = true;
- dep.loc = Object.create(expr.loc);
- dep.loc.index = idx;
- this.state.module.addDependency(dep);
- requests.push(request);
- });
- if(expr.arguments.length > 1)
- this.applyPluginsBailResult("hot accept callback", expr.arguments[1], requests);
- else
- this.applyPluginsBailResult("hot accept without callback", expr, requests);
- }
- }
- });
- parser.plugin("call module.hot.decline", function(expr) {
- if(!this.state.compilation.hotUpdateChunkTemplate) return false;
- if(expr.arguments.length === 1) {
- const arg = this.evaluateExpression(expr.arguments[0]);
- let params = [];
- if(arg.isString()) {
- params = [arg];
- } else if(arg.isArray()) {
- params = arg.items.filter(param => param.isString());
- }
- params.forEach((param, idx) => {
- const dep = new ModuleHotDeclineDependency(param.string, param.range);
- dep.optional = true;
- dep.loc = Object.create(expr.loc);
- dep.loc.index = idx;
- this.state.module.addDependency(dep);
- });
- }
- });
- parser.plugin("expression module.hot", ParserHelpers.skipTraversal);
- });
- });
- }
-
-};
-
-const hotInitCode = Template.getFunctionContent(require("./HotModuleReplacement.runtime.js"));
+/* + 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 Template = require("./Template"); +const ModuleHotAcceptDependency = require("./dependencies/ModuleHotAcceptDependency"); +const ModuleHotDeclineDependency = require("./dependencies/ModuleHotDeclineDependency"); +const ConstDependency = require("./dependencies/ConstDependency"); +const NullFactory = require("./NullFactory"); +const ParserHelpers = require("./ParserHelpers"); + +module.exports = class HotModuleReplacementPlugin { + constructor(options) { + this.options = options || {}; + this.multiStep = this.options.multiStep; + this.fullBuildTimeout = this.options.fullBuildTimeout || 200; + this.requestTimeout = this.options.requestTimeout || 10000; + } + + apply(compiler) { + const multiStep = this.multiStep; + const fullBuildTimeout = this.fullBuildTimeout; + const requestTimeout = this.requestTimeout; + const hotUpdateChunkFilename = + compiler.options.output.hotUpdateChunkFilename; + const hotUpdateMainFilename = compiler.options.output.hotUpdateMainFilename; + compiler.hooks.additionalPass.tapAsync( + "HotModuleReplacementPlugin", + callback => { + if (multiStep) return setTimeout(callback, fullBuildTimeout); + return callback(); + } + ); + + const addParserPlugins = (parser, parserOptions) => { + parser.hooks.expression + .for("__webpack_hash__") + .tap( + "HotModuleReplacementPlugin", + ParserHelpers.toConstantDependencyWithWebpackRequire( + parser, + "__webpack_require__.h()" + ) + ); + parser.hooks.evaluateTypeof + .for("__webpack_hash__") + .tap( + "HotModuleReplacementPlugin", + ParserHelpers.evaluateToString("string") + ); + parser.hooks.evaluateIdentifier.for("module.hot").tap( + { + name: "HotModuleReplacementPlugin", + before: "NodeStuffPlugin" + }, + expr => { + return ParserHelpers.evaluateToIdentifier( + "module.hot", + !!parser.state.compilation.hotUpdateChunkTemplate + )(expr); + } + ); + // TODO webpack 5: refactor this, no custom hooks + if (!parser.hooks.hotAcceptCallback) { + parser.hooks.hotAcceptCallback = new SyncBailHook([ + "expression", + "requests" + ]); + } + if (!parser.hooks.hotAcceptWithoutCallback) { + parser.hooks.hotAcceptWithoutCallback = new SyncBailHook([ + "expression", + "requests" + ]); + } + parser.hooks.call + .for("module.hot.accept") + .tap("HotModuleReplacementPlugin", expr => { + if (!parser.state.compilation.hotUpdateChunkTemplate) { + return false; + } + if (expr.arguments.length >= 1) { + const arg = parser.evaluateExpression(expr.arguments[0]); + let params = []; + let requests = []; + if (arg.isString()) { + params = [arg]; + } else if (arg.isArray()) { + params = arg.items.filter(param => param.isString()); + } + if (params.length > 0) { + params.forEach((param, idx) => { + const request = param.string; + const dep = new ModuleHotAcceptDependency(request, param.range); + dep.optional = true; + dep.loc = Object.create(expr.loc); + dep.loc.index = idx; + parser.state.module.addDependency(dep); + requests.push(request); + }); + if (expr.arguments.length > 1) { + parser.hooks.hotAcceptCallback.call( + expr.arguments[1], + requests + ); + parser.walkExpression(expr.arguments[1]); // other args are ignored + return true; + } else { + parser.hooks.hotAcceptWithoutCallback.call(expr, requests); + return true; + } + } + } + }); + parser.hooks.call + .for("module.hot.decline") + .tap("HotModuleReplacementPlugin", expr => { + if (!parser.state.compilation.hotUpdateChunkTemplate) { + return false; + } + if (expr.arguments.length === 1) { + const arg = parser.evaluateExpression(expr.arguments[0]); + let params = []; + if (arg.isString()) { + params = [arg]; + } else if (arg.isArray()) { + params = arg.items.filter(param => param.isString()); + } + params.forEach((param, idx) => { + const dep = new ModuleHotDeclineDependency( + param.string, + param.range + ); + dep.optional = true; + dep.loc = Object.create(expr.loc); + dep.loc.index = idx; + parser.state.module.addDependency(dep); + }); + } + }); + parser.hooks.expression + .for("module.hot") + .tap("HotModuleReplacementPlugin", ParserHelpers.skipTraversal); + }; + + compiler.hooks.compilation.tap( + "HotModuleReplacementPlugin", + (compilation, { normalModuleFactory }) => { + const hotUpdateChunkTemplate = compilation.hotUpdateChunkTemplate; + if (!hotUpdateChunkTemplate) return; + + compilation.dependencyFactories.set(ConstDependency, new NullFactory()); + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); + + compilation.dependencyFactories.set( + ModuleHotAcceptDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + ModuleHotAcceptDependency, + new ModuleHotAcceptDependency.Template() + ); + + compilation.dependencyFactories.set( + ModuleHotDeclineDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + ModuleHotDeclineDependency, + new ModuleHotDeclineDependency.Template() + ); + + compilation.hooks.record.tap( + "HotModuleReplacementPlugin", + (compilation, records) => { + if (records.hash === compilation.hash) return; + records.hash = compilation.hash; + records.moduleHashs = {}; + for (const module of compilation.modules) { + const identifier = module.identifier(); + records.moduleHashs[identifier] = module.hash; + } + records.chunkHashs = {}; + for (const chunk of compilation.chunks) { + records.chunkHashs[chunk.id] = chunk.hash; + } + records.chunkModuleIds = {}; + for (const chunk of compilation.chunks) { + records.chunkModuleIds[chunk.id] = Array.from( + chunk.modulesIterable, + m => m.id + ); + } + } + ); + let initialPass = false; + let recompilation = false; + compilation.hooks.afterHash.tap("HotModuleReplacementPlugin", () => { + let records = compilation.records; + if (!records) { + initialPass = true; + return; + } + if (!records.hash) initialPass = true; + const preHash = records.preHash || "x"; + const prepreHash = records.prepreHash || "x"; + if (preHash === compilation.hash) { + recompilation = true; + compilation.modifyHash(prepreHash); + return; + } + records.prepreHash = records.hash || "x"; + records.preHash = compilation.hash; + compilation.modifyHash(records.prepreHash); + }); + compilation.hooks.shouldGenerateChunkAssets.tap( + "HotModuleReplacementPlugin", + () => { + if (multiStep && !recompilation && !initialPass) return false; + } + ); + compilation.hooks.needAdditionalPass.tap( + "HotModuleReplacementPlugin", + () => { + if (multiStep && !recompilation && !initialPass) return true; + } + ); + compilation.hooks.additionalChunkAssets.tap( + "HotModuleReplacementPlugin", + () => { + const records = compilation.records; + if (records.hash === compilation.hash) return; + if ( + !records.moduleHashs || + !records.chunkHashs || + !records.chunkModuleIds + ) + return; + for (const module of compilation.modules) { + const identifier = module.identifier(); + let hash = module.hash; + module.hotUpdate = records.moduleHashs[identifier] !== hash; + } + const hotUpdateMainContent = { + h: compilation.hash, + c: {} + }; + for (const key of Object.keys(records.chunkHashs)) { + const chunkId = isNaN(+key) ? key : +key; + const currentChunk = compilation.chunks.find( + chunk => chunk.id === chunkId + ); + if (currentChunk) { + const newModules = currentChunk + .getModules() + .filter(module => module.hotUpdate); + const allModules = new Set(); + for (const module of currentChunk.modulesIterable) { + allModules.add(module.id); + } + const removedModules = records.chunkModuleIds[chunkId].filter( + id => !allModules.has(id) + ); + if (newModules.length > 0 || removedModules.length > 0) { + const source = hotUpdateChunkTemplate.render( + chunkId, + newModules, + removedModules, + compilation.hash, + compilation.moduleTemplates.javascript, + compilation.dependencyTemplates + ); + const filename = compilation.getPath(hotUpdateChunkFilename, { + hash: records.hash, + chunk: currentChunk + }); + compilation.additionalChunkAssets.push(filename); + compilation.assets[filename] = source; + hotUpdateMainContent.c[chunkId] = true; + currentChunk.files.push(filename); + compilation.hooks.chunkAsset.call(currentChunk, filename); + } + } else { + hotUpdateMainContent.c[chunkId] = false; + } + } + const source = new RawSource(JSON.stringify(hotUpdateMainContent)); + const filename = compilation.getPath(hotUpdateMainFilename, { + hash: records.hash + }); + compilation.assets[filename] = source; + } + ); + + const mainTemplate = compilation.mainTemplate; + + mainTemplate.hooks.hash.tap("HotModuleReplacementPlugin", hash => { + hash.update("HotMainTemplateDecorator"); + }); + + mainTemplate.hooks.moduleRequire.tap( + "HotModuleReplacementPlugin", + (_, chunk, hash, varModuleId) => { + return `hotCreateRequire(${varModuleId})`; + } + ); + + mainTemplate.hooks.requireExtensions.tap( + "HotModuleReplacementPlugin", + source => { + const buf = [source]; + buf.push(""); + buf.push("// __webpack_hash__"); + buf.push( + mainTemplate.requireFn + + ".h = function() { return hotCurrentHash; };" + ); + return Template.asString(buf); + } + ); + + const needChunkLoadingCode = chunk => { + for (const chunkGroup of chunk.groupsIterable) { + if (chunkGroup.chunks.length > 1) return true; + if (chunkGroup.getNumberOfChildren() > 0) return true; + } + return false; + }; + + mainTemplate.hooks.bootstrap.tap( + "HotModuleReplacementPlugin", + (source, chunk, hash) => { + source = mainTemplate.hooks.hotBootstrap.call(source, chunk, hash); + return Template.asString([ + source, + "", + hotInitCode + .replace(/\$require\$/g, mainTemplate.requireFn) + .replace(/\$hash\$/g, JSON.stringify(hash)) + .replace(/\$requestTimeout\$/g, requestTimeout) + .replace( + /\/\*foreachInstalledChunks\*\//g, + needChunkLoadingCode(chunk) + ? "for(var chunkId in installedChunks)" + : `var chunkId = ${JSON.stringify(chunk.id)};` + ) + ]); + } + ); + + mainTemplate.hooks.globalHash.tap( + "HotModuleReplacementPlugin", + () => true + ); + + mainTemplate.hooks.currentHash.tap( + "HotModuleReplacementPlugin", + (_, length) => { + if (isFinite(length)) { + return `hotCurrentHash.substr(0, ${length})`; + } else { + return "hotCurrentHash"; + } + } + ); + + mainTemplate.hooks.moduleObj.tap( + "HotModuleReplacementPlugin", + (source, chunk, hash, varModuleId) => { + return Template.asString([ + `${source},`, + `hot: hotCreateModule(${varModuleId}),`, + "parents: (hotCurrentParentsTemp = hotCurrentParents, hotCurrentParents = [], hotCurrentParentsTemp),", + "children: []" + ]); + } + ); + + // TODO add HMR support for javascript/esm + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("HotModuleReplacementPlugin", addParserPlugins); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("HotModuleReplacementPlugin", addParserPlugins); + + compilation.hooks.normalModuleLoader.tap( + "HotModuleReplacementPlugin", + context => { + context.hot = true; + } + ); + } + ); + } +}; + +const hotInitCode = Template.getFunctionContent( + require("./HotModuleReplacement.runtime") +); diff --git a/node_modules/webpack/lib/HotUpdateChunkTemplate.js b/node_modules/webpack/lib/HotUpdateChunkTemplate.js index 0a83c9a85..92ab8db08 100644 --- a/node_modules/webpack/lib/HotUpdateChunkTemplate.js +++ b/node_modules/webpack/lib/HotUpdateChunkTemplate.js @@ -1,31 +1,78 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const Template = require("./Template");
-const Chunk = require("./Chunk");
-
-module.exports = class HotUpdateChunkTemplate extends Template {
- constructor(outputOptions) {
- super(outputOptions);
- }
-
- render(id, modules, removedModules, hash, moduleTemplate, dependencyTemplates) {
- const hotUpdateChunk = new Chunk();
- hotUpdateChunk.id = id;
- hotUpdateChunk.setModules(modules);
- hotUpdateChunk.removedModules = removedModules;
- const modulesSource = this.renderChunkModules(hotUpdateChunk, moduleTemplate, dependencyTemplates);
- const core = this.applyPluginsWaterfall("modules", modulesSource, modules, removedModules, moduleTemplate, dependencyTemplates);
- const source = this.applyPluginsWaterfall("render", core, modules, removedModules, hash, id, moduleTemplate, dependencyTemplates);
- return source;
- }
-
- updateHash(hash) {
- hash.update("HotUpdateChunkTemplate");
- hash.update("1");
- this.applyPlugins("hash", hash);
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Template = require("./Template"); +const HotUpdateChunk = require("./HotUpdateChunk"); +const { Tapable, SyncWaterfallHook, SyncHook } = require("tapable"); + +module.exports = class HotUpdateChunkTemplate extends Tapable { + constructor(outputOptions) { + super(); + this.outputOptions = outputOptions || {}; + this.hooks = { + modules: new SyncWaterfallHook([ + "source", + "modules", + "removedModules", + "moduleTemplate", + "dependencyTemplates" + ]), + render: new SyncWaterfallHook([ + "source", + "modules", + "removedModules", + "hash", + "id", + "moduleTemplate", + "dependencyTemplates" + ]), + hash: new SyncHook(["hash"]) + }; + } + + render( + id, + modules, + removedModules, + hash, + moduleTemplate, + dependencyTemplates + ) { + const hotUpdateChunk = new HotUpdateChunk(); + hotUpdateChunk.id = id; + hotUpdateChunk.setModules(modules); + hotUpdateChunk.removedModules = removedModules; + const modulesSource = Template.renderChunkModules( + hotUpdateChunk, + m => typeof m.source === "function", + moduleTemplate, + dependencyTemplates + ); + const core = this.hooks.modules.call( + modulesSource, + modules, + removedModules, + moduleTemplate, + dependencyTemplates + ); + const source = this.hooks.render.call( + core, + modules, + removedModules, + hash, + id, + moduleTemplate, + dependencyTemplates + ); + return source; + } + + updateHash(hash) { + hash.update("HotUpdateChunkTemplate"); + hash.update("1"); + this.hooks.hash.call(hash); + } +}; diff --git a/node_modules/webpack/lib/IgnorePlugin.js b/node_modules/webpack/lib/IgnorePlugin.js index d8f2db018..6e803e8ff 100644 --- a/node_modules/webpack/lib/IgnorePlugin.js +++ b/node_modules/webpack/lib/IgnorePlugin.js @@ -1,69 +1,109 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-class IgnorePlugin {
- constructor(resourceRegExp, contextRegExp) {
- this.resourceRegExp = resourceRegExp;
- this.contextRegExp = contextRegExp;
-
- this.checkIgnore = this.checkIgnore.bind(this);
- }
-
- /*
- * Only returns true if a "resourceRegExp" exists
- * and the resource given matches the regexp.
- */
- checkResource(resource) {
- if(!this.resourceRegExp) {
- return false;
- }
- return this.resourceRegExp.test(resource);
- }
-
- /*
- * Returns true if contextRegExp does not exist
- * or if context matches the given regexp.
- */
- checkContext(context) {
- if(!this.contextRegExp) {
- return true;
- }
- return this.contextRegExp.test(context);
- }
-
- /*
- * Returns true if result should be ignored.
- * false if it shouldn't.
- *
- * Not that if "contextRegExp" is given, both the "resourceRegExp"
- * and "contextRegExp" have to match.
- */
- checkResult(result) {
- if(!result) {
- return true;
- }
- return this.checkResource(result.request) && this.checkContext(result.context);
- }
-
- checkIgnore(result, callback) {
- // check if result is ignored
- if(this.checkResult(result)) {
- return callback();
- }
- return callback(null, result);
- }
-
- apply(compiler) {
- compiler.plugin("normal-module-factory", (nmf) => {
- nmf.plugin("before-resolve", this.checkIgnore);
- });
- compiler.plugin("context-module-factory", (cmf) => {
- cmf.plugin("before-resolve", this.checkIgnore);
- });
- }
-}
-
-module.exports = IgnorePlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const validateOptions = require("schema-utils"); +const schema = require("../schemas/plugins/IgnorePlugin.json"); + +/** @typedef {import("./Compiler")} Compiler */ + +class IgnorePlugin { + /** + * @param {object} options IgnorePlugin options + * @param {RegExp} options.resourceRegExp - A RegExp to test the request against + * @param {RegExp} options.contextRegExp - A RegExp to test the context (directory) against + * @param {function(string): boolean=} options.checkResource - A filter function for resource + * @param {function(string): boolean=} options.checkContext - A filter function for context + */ + constructor(options) { + // TODO webpack 5 remove this compat-layer + if (arguments.length > 1 || options instanceof RegExp) { + options = { + resourceRegExp: arguments[0], + contextRegExp: arguments[1] + }; + } + + validateOptions(schema, options, "IgnorePlugin"); + this.options = options; + + /** @private @type {Function} */ + this.checkIgnore = this.checkIgnore.bind(this); + } + + /** + * @param {string} resource resource + * @returns {boolean} returns true if a "resourceRegExp" exists + * and the resource given matches the regexp. + */ + checkResource(resource) { + if (this.options.checkResource) { + return this.options.checkResource(resource); + } + if (!this.options.resourceRegExp) { + return false; + } + return this.options.resourceRegExp.test(resource); + } + + /** + * @param {string} context context + * @returns {boolean} returns true if "contextRegExp" does not exist + * or if context matches the given regexp. + */ + checkContext(context) { + if (this.options.checkContext) { + return this.options.checkContext(context); + } + + if (!this.options.contextRegExp) { + return true; + } + return this.options.contextRegExp.test(context); + } + + /** + * Note that if "contextRegExp" is given, both the "resourceRegExp" + * and "contextRegExp" have to match. + * + * @param {TODO} result result + * @returns {boolean} returns true if result should be ignored + */ + checkResult(result) { + if (!result) { + return true; + } + return ( + this.checkResource(result.request) && this.checkContext(result.context) + ); + } + + /** + * @param {TODO} result result + * @returns {TODO|null} returns result or null if result should be ignored + */ + checkIgnore(result) { + // check if result is ignored + if (this.checkResult(result)) { + return null; + } + return result; + } + + /** + * @param {Compiler} compiler Webpack Compiler + * @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; diff --git a/node_modules/webpack/lib/JsonpChunkTemplatePlugin.js b/node_modules/webpack/lib/JsonpChunkTemplatePlugin.js deleted file mode 100644 index ceeb95406..000000000 --- a/node_modules/webpack/lib/JsonpChunkTemplatePlugin.js +++ /dev/null @@ -1,31 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const ConcatSource = require("webpack-sources").ConcatSource;
-
-class JsonpChunkTemplatePlugin {
- apply(chunkTemplate) {
- chunkTemplate.plugin("render", function(modules, chunk) {
- const jsonpFunction = this.outputOptions.jsonpFunction;
- const source = new ConcatSource();
- source.add(`${jsonpFunction}(${JSON.stringify(chunk.ids)},`);
- source.add(modules);
- const entries = [chunk.entryModule].filter(Boolean).map(m => m.id);
- if(entries.length > 0) {
- source.add(`,${JSON.stringify(entries)}`);
- }
- source.add(")");
- return source;
- });
- chunkTemplate.plugin("hash", function(hash) {
- hash.update("JsonpChunkTemplatePlugin");
- hash.update("3");
- hash.update(`${this.outputOptions.jsonpFunction}`);
- hash.update(`${this.outputOptions.library}`);
- });
- }
-}
-module.exports = JsonpChunkTemplatePlugin;
diff --git a/node_modules/webpack/lib/JsonpExportMainTemplatePlugin.js b/node_modules/webpack/lib/JsonpExportMainTemplatePlugin.js deleted file mode 100644 index 8bbab2e04..000000000 --- a/node_modules/webpack/lib/JsonpExportMainTemplatePlugin.js +++ /dev/null @@ -1,37 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const ConcatSource = require("webpack-sources").ConcatSource;
-
-class JsonpExportMainTemplatePlugin {
- constructor(name) {
- this.name = name;
- }
-
- apply(compilation) {
- const mainTemplate = compilation.mainTemplate;
-
- compilation.templatesPlugin("render-with-entry", (source, chunk, hash) => {
- const name = mainTemplate.applyPluginsWaterfall("asset-path", this.name || "", {
- hash: hash,
- chunk: chunk
- });
- return new ConcatSource(`${name}(`, source, ");");
- });
-
- mainTemplate.plugin("global-hash-paths", paths => {
- if(this.name) paths.push(this.name);
- return paths;
- });
-
- mainTemplate.plugin("hash", hash => {
- hash.update("jsonp export");
- hash.update(`${this.name}`);
- });
- }
-}
-
-module.exports = JsonpExportMainTemplatePlugin;
diff --git a/node_modules/webpack/lib/JsonpHotUpdateChunkTemplatePlugin.js b/node_modules/webpack/lib/JsonpHotUpdateChunkTemplatePlugin.js deleted file mode 100644 index 407110e93..000000000 --- a/node_modules/webpack/lib/JsonpHotUpdateChunkTemplatePlugin.js +++ /dev/null @@ -1,27 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const ConcatSource = require("webpack-sources").ConcatSource;
-
-class JsonpHotUpdateChunkTemplatePlugin {
- apply(hotUpdateChunkTemplate) {
- hotUpdateChunkTemplate.plugin("render", function(modulesSource, modules, removedModules, hash, id) {
- const source = new ConcatSource();
- source.add(`${this.outputOptions.hotUpdateFunction}(${JSON.stringify(id)},`);
- source.add(modulesSource);
- source.add(")");
- return source;
- });
- hotUpdateChunkTemplate.plugin("hash", function(hash) {
- hash.update("JsonpHotUpdateChunkTemplatePlugin");
- hash.update("3");
- hash.update(`${this.outputOptions.hotUpdateFunction}`);
- hash.update(`${this.outputOptions.library}`);
- });
- }
-}
-
-module.exports = JsonpHotUpdateChunkTemplatePlugin;
diff --git a/node_modules/webpack/lib/JsonpMainTemplate.runtime.js b/node_modules/webpack/lib/JsonpMainTemplate.runtime.js deleted file mode 100644 index ed5fba098..000000000 --- a/node_modules/webpack/lib/JsonpMainTemplate.runtime.js +++ /dev/null @@ -1,60 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-/*globals hotAddUpdateChunk parentHotUpdateCallback document XMLHttpRequest $require$ $hotChunkFilename$ $hotMainFilename$ $crossOriginLoading$ */
-module.exports = function() {
- function webpackHotUpdateCallback(chunkId, moreModules) { // eslint-disable-line no-unused-vars
- hotAddUpdateChunk(chunkId, moreModules);
- if(parentHotUpdateCallback) parentHotUpdateCallback(chunkId, moreModules);
- } //$semicolon
-
- function hotDownloadUpdateChunk(chunkId) { // eslint-disable-line no-unused-vars
- var head = document.getElementsByTagName("head")[0];
- var script = document.createElement("script");
- script.type = "text/javascript";
- script.charset = "utf-8";
- script.src = $require$.p + $hotChunkFilename$;
- $crossOriginLoading$;
- head.appendChild(script);
- }
-
- function hotDownloadManifest(requestTimeout) { // eslint-disable-line no-unused-vars
- requestTimeout = requestTimeout || 10000;
- return new Promise(function(resolve, reject) {
- if(typeof XMLHttpRequest === "undefined")
- return reject(new Error("No browser support"));
- try {
- var request = new XMLHttpRequest();
- var requestPath = $require$.p + $hotMainFilename$;
- request.open("GET", requestPath, true);
- request.timeout = requestTimeout;
- request.send(null);
- } catch(err) {
- return reject(err);
- }
- request.onreadystatechange = function() {
- if(request.readyState !== 4) return;
- if(request.status === 0) {
- // timeout
- reject(new Error("Manifest request to " + requestPath + " timed out."));
- } else if(request.status === 404) {
- // no update available
- resolve();
- } else if(request.status !== 200 && request.status !== 304) {
- // other failure
- reject(new Error("Manifest request to " + requestPath + " failed."));
- } else {
- // success
- try {
- var update = JSON.parse(request.responseText);
- } catch(e) {
- reject(e);
- return;
- }
- resolve(update);
- }
- };
- });
- }
-};
diff --git a/node_modules/webpack/lib/JsonpMainTemplatePlugin.js b/node_modules/webpack/lib/JsonpMainTemplatePlugin.js deleted file mode 100644 index e713f3879..000000000 --- a/node_modules/webpack/lib/JsonpMainTemplatePlugin.js +++ /dev/null @@ -1,211 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const Template = require("./Template");
-
-class JsonpMainTemplatePlugin {
-
- apply(mainTemplate) {
- mainTemplate.plugin("local-vars", function(source, chunk) {
- if(chunk.chunks.length > 0) {
- return this.asString([
- source,
- "",
- "// objects to store loaded and loading chunks",
- "var installedChunks = {",
- this.indent(
- chunk.ids.map(id => `${JSON.stringify(id)}: 0`).join(",\n")
- ),
- "};"
- ]);
- }
- return source;
- });
- mainTemplate.plugin("jsonp-script", function(_, chunk, hash) {
- const chunkFilename = this.outputOptions.chunkFilename;
- const chunkMaps = chunk.getChunkMaps();
- const crossOriginLoading = this.outputOptions.crossOriginLoading;
- const chunkLoadTimeout = this.outputOptions.chunkLoadTimeout;
- const scriptSrcPath = this.applyPluginsWaterfall("asset-path", JSON.stringify(chunkFilename), {
- hash: `" + ${this.renderCurrentHashCode(hash)} + "`,
- hashWithLength: length => `" + ${this.renderCurrentHashCode(hash, length)} + "`,
- chunk: {
- id: "\" + chunkId + \"",
- hash: `" + ${JSON.stringify(chunkMaps.hash)}[chunkId] + "`,
- hashWithLength(length) {
- const shortChunkHashMap = Object.create(null);
- Object.keys(chunkMaps.hash).forEach(chunkId => {
- if(typeof chunkMaps.hash[chunkId] === "string")
- shortChunkHashMap[chunkId] = chunkMaps.hash[chunkId].substr(0, length);
- });
- return `" + ${JSON.stringify(shortChunkHashMap)}[chunkId] + "`;
- },
- name: `" + (${JSON.stringify(chunkMaps.name)}[chunkId]||chunkId) + "`
- }
- });
- return this.asString([
- "var script = document.createElement('script');",
- "script.type = 'text/javascript';",
- "script.charset = 'utf-8';",
- "script.async = true;",
- `script.timeout = ${chunkLoadTimeout};`,
- crossOriginLoading ? `script.crossOrigin = ${JSON.stringify(crossOriginLoading)};` : "",
- `if (${this.requireFn}.nc) {`,
- this.indent(`script.setAttribute("nonce", ${this.requireFn}.nc);`),
- "}",
- `script.src = ${this.requireFn}.p + ${scriptSrcPath};`,
- `var timeout = setTimeout(onScriptComplete, ${chunkLoadTimeout});`,
- "script.onerror = script.onload = onScriptComplete;",
- "function onScriptComplete() {",
- this.indent([
- "// avoid mem leaks in IE.",
- "script.onerror = script.onload = null;",
- "clearTimeout(timeout);",
- "var chunk = installedChunks[chunkId];",
- "if(chunk !== 0) {",
- this.indent([
- "if(chunk) {",
- this.indent("chunk[1](new Error('Loading chunk ' + chunkId + ' failed.'));"),
- "}",
- "installedChunks[chunkId] = undefined;"
- ]),
- "}"
- ]),
- "};",
- ]);
- });
- mainTemplate.plugin("require-ensure", function(_, chunk, hash) {
- return this.asString([
- "var installedChunkData = installedChunks[chunkId];",
- "if(installedChunkData === 0) {",
- this.indent([
- "return new Promise(function(resolve) { resolve(); });"
- ]),
- "}",
- "",
- "// a Promise means \"currently loading\".",
- "if(installedChunkData) {",
- this.indent([
- "return installedChunkData[2];"
- ]),
- "}",
- "",
- "// setup Promise in chunk cache",
- "var promise = new Promise(function(resolve, reject) {",
- this.indent([
- "installedChunkData = installedChunks[chunkId] = [resolve, reject];"
- ]),
- "});",
- "installedChunkData[2] = promise;",
- "",
- "// start chunk loading",
- "var head = document.getElementsByTagName('head')[0];",
- this.applyPluginsWaterfall("jsonp-script", "", chunk, hash),
- "head.appendChild(script);",
- "",
- "return promise;"
- ]);
- });
- mainTemplate.plugin("require-extensions", function(source, chunk) {
- if(chunk.chunks.length === 0) return source;
-
- return this.asString([
- source,
- "",
- "// on error function for async loading",
- `${this.requireFn}.oe = function(err) { console.error(err); throw err; };`
- ]);
- });
- mainTemplate.plugin("bootstrap", function(source, chunk, hash) {
- if(chunk.chunks.length > 0) {
- var jsonpFunction = this.outputOptions.jsonpFunction;
- return this.asString([
- source,
- "",
- "// install a JSONP callback for chunk loading",
- `var parentJsonpFunction = window[${JSON.stringify(jsonpFunction)}];`,
- `window[${JSON.stringify(jsonpFunction)}] = function webpackJsonpCallback(chunkIds, moreModules, executeModules) {`,
- this.indent([
- "// add \"moreModules\" to the modules object,",
- "// then flag all \"chunkIds\" as loaded and fire callback",
- "var moduleId, chunkId, i = 0, resolves = [], result;",
- "for(;i < chunkIds.length; i++) {",
- this.indent([
- "chunkId = chunkIds[i];",
- "if(installedChunks[chunkId]) {",
- this.indent("resolves.push(installedChunks[chunkId][0]);"),
- "}",
- "installedChunks[chunkId] = 0;"
- ]),
- "}",
- "for(moduleId in moreModules) {",
- this.indent([
- "if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {",
- this.indent(this.renderAddModule(hash, chunk, "moduleId", "moreModules[moduleId]")),
- "}"
- ]),
- "}",
- "if(parentJsonpFunction) parentJsonpFunction(chunkIds, moreModules, executeModules);",
- "while(resolves.length) {",
- this.indent("resolves.shift()();"),
- "}",
- this.entryPointInChildren(chunk) ? [
- "if(executeModules) {",
- this.indent([
- "for(i=0; i < executeModules.length; i++) {",
- this.indent(`result = ${this.requireFn}(${this.requireFn}.s = executeModules[i]);`),
- "}"
- ]),
- "}",
- "return result;",
- ] : ""
- ]),
- "};"
- ]);
- }
- return source;
- });
- mainTemplate.plugin("hot-bootstrap", function(source, chunk, hash) {
- const hotUpdateChunkFilename = this.outputOptions.hotUpdateChunkFilename;
- const hotUpdateMainFilename = this.outputOptions.hotUpdateMainFilename;
- const crossOriginLoading = this.outputOptions.crossOriginLoading;
- const hotUpdateFunction = this.outputOptions.hotUpdateFunction;
- const currentHotUpdateChunkFilename = this.applyPluginsWaterfall("asset-path", JSON.stringify(hotUpdateChunkFilename), {
- hash: `" + ${this.renderCurrentHashCode(hash)} + "`,
- hashWithLength: length => `" + ${this.renderCurrentHashCode(hash, length)} + "`,
- chunk: {
- id: "\" + chunkId + \""
- }
- });
- const currentHotUpdateMainFilename = this.applyPluginsWaterfall("asset-path", JSON.stringify(hotUpdateMainFilename), {
- hash: `" + ${this.renderCurrentHashCode(hash)} + "`,
- hashWithLength: length => `" + ${this.renderCurrentHashCode(hash, length)} + "`
- });
- const runtimeSource = Template.getFunctionContent(require("./JsonpMainTemplate.runtime.js"))
- .replace(/\/\/\$semicolon/g, ";")
- .replace(/\$require\$/g, this.requireFn)
- .replace(/\$crossOriginLoading\$/g, crossOriginLoading ? `script.crossOrigin = ${JSON.stringify(crossOriginLoading)}` : "")
- .replace(/\$hotMainFilename\$/g, currentHotUpdateMainFilename)
- .replace(/\$hotChunkFilename\$/g, currentHotUpdateChunkFilename)
- .replace(/\$hash\$/g, JSON.stringify(hash));
- return `${source}
-function hotDisposeChunk(chunkId) {
- delete installedChunks[chunkId];
-}
-var parentHotUpdateCallback = window[${JSON.stringify(hotUpdateFunction)}];
-window[${JSON.stringify(hotUpdateFunction)}] = ${runtimeSource}`;
- });
- mainTemplate.plugin("hash", function(hash) {
- hash.update("jsonp");
- hash.update("4");
- hash.update(`${this.outputOptions.filename}`);
- hash.update(`${this.outputOptions.chunkFilename}`);
- hash.update(`${this.outputOptions.jsonpFunction}`);
- hash.update(`${this.outputOptions.hotUpdateFunction}`);
- });
- }
-}
-module.exports = JsonpMainTemplatePlugin;
diff --git a/node_modules/webpack/lib/JsonpTemplatePlugin.js b/node_modules/webpack/lib/JsonpTemplatePlugin.js deleted file mode 100644 index a141891f7..000000000 --- a/node_modules/webpack/lib/JsonpTemplatePlugin.js +++ /dev/null @@ -1,21 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const JsonpMainTemplatePlugin = require("./JsonpMainTemplatePlugin");
-const JsonpChunkTemplatePlugin = require("./JsonpChunkTemplatePlugin");
-const JsonpHotUpdateChunkTemplatePlugin = require("./JsonpHotUpdateChunkTemplatePlugin");
-
-class JsonpTemplatePlugin {
- apply(compiler) {
- compiler.plugin("this-compilation", (compilation) => {
- compilation.mainTemplate.apply(new JsonpMainTemplatePlugin());
- compilation.chunkTemplate.apply(new JsonpChunkTemplatePlugin());
- compilation.hotUpdateChunkTemplate.apply(new JsonpHotUpdateChunkTemplatePlugin());
- });
- }
-}
-
-module.exports = JsonpTemplatePlugin;
diff --git a/node_modules/webpack/lib/LibManifestPlugin.js b/node_modules/webpack/lib/LibManifestPlugin.js index dc2f0ae14..54dbf10a0 100644 --- a/node_modules/webpack/lib/LibManifestPlugin.js +++ b/node_modules/webpack/lib/LibManifestPlugin.js @@ -1,63 +1,86 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const path = require("path");
-const asyncLib = require("async");
-
-class LibManifestPlugin {
- constructor(options) {
- this.options = options;
- }
-
- apply(compiler) {
- compiler.plugin("emit", (compilation, callback) => {
- asyncLib.forEach(compilation.chunks, (chunk, callback) => {
- if(!chunk.isInitial()) {
- callback();
- return;
- }
- const targetPath = compilation.getPath(this.options.path, {
- hash: compilation.hash,
- chunk
- });
- const name = this.options.name && compilation.getPath(this.options.name, {
- hash: compilation.hash,
- chunk
- });
- const manifest = {
- name,
- type: this.options.type,
- content: chunk.mapModules(module => {
- if(module.libIdent) {
- const ident = module.libIdent({
- context: this.options.context || compiler.options.context
- });
- if(ident) {
- return {
- ident,
- data: {
- id: module.id,
- meta: module.meta,
- exports: Array.isArray(module.providedExports) ? module.providedExports : undefined
- }
- };
- }
- }
- }).filter(Boolean).reduce((obj, item) => {
- obj[item.ident] = item.data;
- return obj;
- }, Object.create(null))
- };
- const content = new Buffer(JSON.stringify(manifest), "utf8"); //eslint-disable-line
- compiler.outputFileSystem.mkdirp(path.dirname(targetPath), err => {
- if(err) return callback(err);
- compiler.outputFileSystem.writeFile(targetPath, content, callback);
- });
- }, callback);
- });
- }
-}
-module.exports = LibManifestPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const path = require("path"); +const asyncLib = require("neo-async"); +const SingleEntryDependency = require("./dependencies/SingleEntryDependency"); + +class LibManifestPlugin { + constructor(options) { + this.options = options; + } + + apply(compiler) { + compiler.hooks.emit.tapAsync( + "LibManifestPlugin", + (compilation, callback) => { + asyncLib.forEach( + compilation.chunks, + (chunk, callback) => { + if (!chunk.isOnlyInitial()) { + callback(); + return; + } + const targetPath = compilation.getPath(this.options.path, { + hash: compilation.hash, + chunk + }); + const name = + this.options.name && + compilation.getPath(this.options.name, { + hash: compilation.hash, + chunk + }); + const manifest = { + name, + type: this.options.type, + content: Array.from(chunk.modulesIterable, module => { + if ( + this.options.entryOnly && + !module.reasons.some( + r => r.dependency instanceof SingleEntryDependency + ) + ) { + return; + } + if (module.libIdent) { + const ident = module.libIdent({ + context: this.options.context || compiler.options.context + }); + if (ident) { + return { + ident, + data: { + id: module.id, + buildMeta: module.buildMeta + } + }; + } + } + }) + .filter(Boolean) + .reduce((obj, item) => { + obj[item.ident] = item.data; + return obj; + }, Object.create(null)) + }; + const content = Buffer.from(JSON.stringify(manifest), "utf8"); + compiler.outputFileSystem.mkdirp(path.dirname(targetPath), err => { + if (err) return callback(err); + compiler.outputFileSystem.writeFile( + targetPath, + content, + callback + ); + }); + }, + callback + ); + } + ); + } +} +module.exports = LibManifestPlugin; diff --git a/node_modules/webpack/lib/LibraryTemplatePlugin.js b/node_modules/webpack/lib/LibraryTemplatePlugin.js index 11ab06074..c871994fa 100644 --- a/node_modules/webpack/lib/LibraryTemplatePlugin.js +++ b/node_modules/webpack/lib/LibraryTemplatePlugin.js @@ -1,92 +1,153 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const SetVarMainTemplatePlugin = require("./SetVarMainTemplatePlugin");
-
-function accessorToObjectAccess(accessor) {
- return accessor.map((a) => {
- return `[${JSON.stringify(a)}]`;
- }).join("");
-}
-
-function accessorAccess(base, accessor, joinWith) {
- accessor = [].concat(accessor);
- return accessor.map((a, idx) => {
- a = base ?
- base + accessorToObjectAccess(accessor.slice(0, idx + 1)) :
- accessor[0] + accessorToObjectAccess(accessor.slice(1, idx + 1));
- if(idx === accessor.length - 1) return a;
- if(idx === 0 && typeof base === "undefined") return `${a} = typeof ${a} === "object" ? ${a} : {}`;
- return `${a} = ${a} || {}`;
- }).join(joinWith || "; ");
-}
-
-class LibraryTemplatePlugin {
-
- constructor(name, target, umdNamedDefine, auxiliaryComment, exportProperty) {
- this.name = name;
- this.target = target;
- this.umdNamedDefine = umdNamedDefine;
- this.auxiliaryComment = auxiliaryComment;
- this.exportProperty = exportProperty;
- }
-
- apply(compiler) {
- compiler.plugin("this-compilation", (compilation) => {
- if(this.exportProperty) {
- var ExportPropertyMainTemplatePlugin = require("./ExportPropertyMainTemplatePlugin");
- compilation.apply(new ExportPropertyMainTemplatePlugin(this.exportProperty));
- }
- switch(this.target) {
- case "var":
- compilation.apply(new SetVarMainTemplatePlugin(`var ${accessorAccess(false, this.name)}`));
- break;
- case "assign":
- compilation.apply(new SetVarMainTemplatePlugin(accessorAccess(undefined, this.name)));
- break;
- case "this":
- case "window":
- case "global":
- if(this.name)
- compilation.apply(new SetVarMainTemplatePlugin(accessorAccess(this.target, this.name)));
- else
- compilation.apply(new SetVarMainTemplatePlugin(this.target, true));
- break;
- case "commonjs":
- if(this.name)
- compilation.apply(new SetVarMainTemplatePlugin(accessorAccess("exports", this.name)));
- else
- compilation.apply(new SetVarMainTemplatePlugin("exports", true));
- break;
- case "commonjs2":
- case "commonjs-module":
- compilation.apply(new SetVarMainTemplatePlugin("module.exports"));
- break;
- case "amd":
- var AmdMainTemplatePlugin = require("./AmdMainTemplatePlugin");
- compilation.apply(new AmdMainTemplatePlugin(this.name));
- break;
- case "umd":
- case "umd2":
- var UmdMainTemplatePlugin = require("./UmdMainTemplatePlugin");
- compilation.apply(new UmdMainTemplatePlugin(this.name, {
- optionalAmdExternalAsGlobal: this.target === "umd2",
- namedDefine: this.umdNamedDefine,
- auxiliaryComment: this.auxiliaryComment
- }));
- break;
- case "jsonp":
- var JsonpExportMainTemplatePlugin = require("./JsonpExportMainTemplatePlugin");
- compilation.apply(new JsonpExportMainTemplatePlugin(this.name));
- break;
- default:
- throw new Error(`${this.target} is not a valid Library target`);
- }
- });
- }
-}
-
-module.exports = LibraryTemplatePlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const SetVarMainTemplatePlugin = require("./SetVarMainTemplatePlugin"); + +/** @typedef {import("./Compiler")} Compiler */ + +/** + * @param {string[]} accessor the accessor to convert to path + * @returns {string} the path + */ +const accessorToObjectAccess = accessor => { + return accessor.map(a => `[${JSON.stringify(a)}]`).join(""); +}; + +/** + * @param {string=} base the path prefix + * @param {string|string[]} accessor the accessor + * @param {string=} joinWith the element separator + * @returns {string} the path + */ +const accessorAccess = (base, accessor, joinWith = "; ") => { + const accessors = Array.isArray(accessor) ? accessor : [accessor]; + return accessors + .map((_, idx) => { + const a = base + ? base + accessorToObjectAccess(accessors.slice(0, idx + 1)) + : accessors[0] + accessorToObjectAccess(accessors.slice(1, idx + 1)); + if (idx === accessors.length - 1) return a; + if (idx === 0 && base === undefined) { + return `${a} = typeof ${a} === "object" ? ${a} : {}`; + } + return `${a} = ${a} || {}`; + }) + .join(joinWith); +}; + +class LibraryTemplatePlugin { + /** + * @param {string} name name of library + * @param {string} target type of library + * @param {boolean} umdNamedDefine setting this to true will name the UMD module + * @param {string|TODO} auxiliaryComment comment in the UMD wrapper + * @param {string|string[]} exportProperty which export should be exposed as library + */ + constructor(name, target, umdNamedDefine, auxiliaryComment, exportProperty) { + this.name = name; + this.target = target; + this.umdNamedDefine = umdNamedDefine; + this.auxiliaryComment = auxiliaryComment; + this.exportProperty = exportProperty; + } + + /** + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap("LibraryTemplatePlugin", compilation => { + if (this.exportProperty) { + const ExportPropertyMainTemplatePlugin = require("./ExportPropertyMainTemplatePlugin"); + new ExportPropertyMainTemplatePlugin(this.exportProperty).apply( + compilation + ); + } + switch (this.target) { + case "var": + new SetVarMainTemplatePlugin( + `var ${accessorAccess(undefined, this.name)}`, + false + ).apply(compilation); + break; + case "assign": + new SetVarMainTemplatePlugin( + accessorAccess(undefined, this.name), + false + ).apply(compilation); + break; + case "this": + case "self": + case "window": + if (this.name) { + new SetVarMainTemplatePlugin( + accessorAccess(this.target, this.name), + false + ).apply(compilation); + } else { + new SetVarMainTemplatePlugin(this.target, true).apply(compilation); + } + break; + case "global": + if (this.name) { + new SetVarMainTemplatePlugin( + accessorAccess( + compilation.runtimeTemplate.outputOptions.globalObject, + this.name + ), + false + ).apply(compilation); + } else { + new SetVarMainTemplatePlugin( + compilation.runtimeTemplate.outputOptions.globalObject, + true + ).apply(compilation); + } + break; + case "commonjs": + if (this.name) { + new SetVarMainTemplatePlugin( + accessorAccess("exports", this.name), + false + ).apply(compilation); + } else { + new SetVarMainTemplatePlugin("exports", true).apply(compilation); + } + break; + case "commonjs2": + case "commonjs-module": + new SetVarMainTemplatePlugin("module.exports", false).apply( + compilation + ); + break; + case "amd": { + const AmdMainTemplatePlugin = require("./AmdMainTemplatePlugin"); + new AmdMainTemplatePlugin(this.name).apply(compilation); + break; + } + case "umd": + case "umd2": { + const UmdMainTemplatePlugin = require("./UmdMainTemplatePlugin"); + new UmdMainTemplatePlugin(this.name, { + optionalAmdExternalAsGlobal: this.target === "umd2", + namedDefine: this.umdNamedDefine, + auxiliaryComment: this.auxiliaryComment + }).apply(compilation); + break; + } + case "jsonp": { + const JsonpExportMainTemplatePlugin = require("./web/JsonpExportMainTemplatePlugin"); + new JsonpExportMainTemplatePlugin(this.name).apply(compilation); + break; + } + default: + throw new Error(`${this.target} is not a valid Library target`); + } + }); + } +} + +module.exports = LibraryTemplatePlugin; diff --git a/node_modules/webpack/lib/LoaderOptionsPlugin.js b/node_modules/webpack/lib/LoaderOptionsPlugin.js index b3d3ef7f4..5d13e2c06 100644 --- a/node_modules/webpack/lib/LoaderOptionsPlugin.js +++ b/node_modules/webpack/lib/LoaderOptionsPlugin.js @@ -1,36 +1,53 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
-
-class LoaderOptionsPlugin {
- constructor(options) {
- if(typeof options !== "object") options = {};
- if(!options.test) options.test = {
- test: () => true
- };
- this.options = options;
- }
-
- apply(compiler) {
- const options = this.options;
- compiler.plugin("compilation", (compilation) => {
- compilation.plugin("normal-module-loader", (context, module) => {
- const resource = module.resource;
- if(!resource) return;
- const i = resource.indexOf("?");
- if(ModuleFilenameHelpers.matchObject(options, i < 0 ? resource : resource.substr(0, i))) {
- const filterSet = new Set(["include", "exclude", "test"]);
- Object.keys(options)
- .filter((key) => !filterSet.has(key))
- .forEach((key) => context[key] = options[key]);
- }
- });
- });
- }
-}
-
-module.exports = LoaderOptionsPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const ModuleFilenameHelpers = require("./ModuleFilenameHelpers"); + +const validateOptions = require("schema-utils"); +const schema = require("../schemas/plugins/LoaderOptionsPlugin.json"); + +class LoaderOptionsPlugin { + constructor(options) { + validateOptions(schema, options || {}, "Loader Options Plugin"); + + if (typeof options !== "object") options = {}; + if (!options.test) { + options.test = { + test: () => true + }; + } + this.options = options; + } + + apply(compiler) { + const options = this.options; + compiler.hooks.compilation.tap("LoaderOptionsPlugin", compilation => { + compilation.hooks.normalModuleLoader.tap( + "LoaderOptionsPlugin", + (context, module) => { + const resource = module.resource; + if (!resource) return; + const i = resource.indexOf("?"); + if ( + ModuleFilenameHelpers.matchObject( + options, + i < 0 ? resource : resource.substr(0, i) + ) + ) { + for (const key of Object.keys(options)) { + if (key === "include" || key === "exclude" || key === "test") { + continue; + } + context[key] = options[key]; + } + } + } + ); + }); + } +} + +module.exports = LoaderOptionsPlugin; diff --git a/node_modules/webpack/lib/LoaderTargetPlugin.js b/node_modules/webpack/lib/LoaderTargetPlugin.js index c7f5f59b4..99ffbc997 100644 --- a/node_modules/webpack/lib/LoaderTargetPlugin.js +++ b/node_modules/webpack/lib/LoaderTargetPlugin.js @@ -1,19 +1,24 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-class LoaderTargetPlugin {
- constructor(target) {
- this.target = target;
- }
-
- apply(compiler) {
- compiler.plugin("compilation", (compilation) => {
- compilation.plugin("normal-module-loader", (loaderContext) => loaderContext.target = this.target);
- });
- }
-}
-
-module.exports = LoaderTargetPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +class LoaderTargetPlugin { + constructor(target) { + this.target = target; + } + + apply(compiler) { + compiler.hooks.compilation.tap("LoaderTargetPlugin", compilation => { + compilation.hooks.normalModuleLoader.tap( + "LoaderTargetPlugin", + loaderContext => { + loaderContext.target = this.target; + } + ); + }); + } +} + +module.exports = LoaderTargetPlugin; diff --git a/node_modules/webpack/lib/MainTemplate.js b/node_modules/webpack/lib/MainTemplate.js index 58a3409d5..0243a4a30 100644 --- a/node_modules/webpack/lib/MainTemplate.js +++ b/node_modules/webpack/lib/MainTemplate.js @@ -1,231 +1,535 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const ConcatSource = require("webpack-sources").ConcatSource;
-const OriginalSource = require("webpack-sources").OriginalSource;
-const PrefixSource = require("webpack-sources").PrefixSource;
-const Template = require("./Template");
-
-// require function shortcuts:
-// __webpack_require__.s = the module id of the entry point
-// __webpack_require__.c = the module cache
-// __webpack_require__.m = the module functions
-// __webpack_require__.p = the bundle public path
-// __webpack_require__.i = the identity function used for harmony imports
-// __webpack_require__.e = the chunk ensure function
-// __webpack_require__.d = the exported propery define getter function
-// __webpack_require__.o = Object.prototype.hasOwnProperty.call
-// __webpack_require__.n = compatibility get default export
-// __webpack_require__.h = the webpack hash
-// __webpack_require__.oe = the uncatched error handler for the webpack runtime
-// __webpack_require__.nc = the script nonce
-
-module.exports = class MainTemplate extends Template {
- constructor(outputOptions) {
- super(outputOptions);
- this.plugin("startup", (source, chunk, hash) => {
- const buf = [];
- if(chunk.entryModule) {
- buf.push("// Load entry module and return exports");
- buf.push(`return ${this.renderRequireFunctionForModule(hash, chunk, JSON.stringify(chunk.entryModule.id))}(${this.requireFn}.s = ${JSON.stringify(chunk.entryModule.id)});`);
- }
- return this.asString(buf);
- });
- this.plugin("render", (bootstrapSource, chunk, hash, moduleTemplate, dependencyTemplates) => {
- const source = new ConcatSource();
- source.add("/******/ (function(modules) { // webpackBootstrap\n");
- source.add(new PrefixSource("/******/", bootstrapSource));
- source.add("/******/ })\n");
- source.add("/************************************************************************/\n");
- source.add("/******/ (");
- const modules = this.renderChunkModules(chunk, moduleTemplate, dependencyTemplates, "/******/ ");
- source.add(this.applyPluginsWaterfall("modules", modules, chunk, hash, moduleTemplate, dependencyTemplates));
- source.add(")");
- return source;
- });
- this.plugin("local-vars", (source, chunk, hash) => {
- return this.asString([
- source,
- "// The module cache",
- "var installedModules = {};"
- ]);
- });
- this.plugin("require", (source, chunk, hash) => {
- return this.asString([
- source,
- "// Check if module is in cache",
- "if(installedModules[moduleId]) {",
- this.indent("return installedModules[moduleId].exports;"),
- "}",
- "// Create a new module (and put it into the cache)",
- "var module = installedModules[moduleId] = {",
- this.indent(this.applyPluginsWaterfall("module-obj", "", chunk, hash, "moduleId")),
- "};",
- "",
- this.asString(outputOptions.strictModuleExceptionHandling ? [
- "// Execute the module function",
- "var threw = true;",
- "try {",
- this.indent([
- `modules[moduleId].call(module.exports, module, module.exports, ${this.renderRequireFunctionForModule(hash, chunk, "moduleId")});`,
- "threw = false;"
- ]),
- "} finally {",
- this.indent([
- "if(threw) delete installedModules[moduleId];"
- ]),
- "}"
- ] : [
- "// Execute the module function",
- `modules[moduleId].call(module.exports, module, module.exports, ${this.renderRequireFunctionForModule(hash, chunk, "moduleId")});`,
- ]),
- "",
- "// Flag the module as loaded",
- "module.l = true;",
- "",
- "// Return the exports of the module",
- "return module.exports;"
- ]);
- });
- this.plugin("module-obj", (source, chunk, hash, varModuleId) => {
- return this.asString([
- "i: moduleId,",
- "l: false,",
- "exports: {}"
- ]);
- });
- this.plugin("require-extensions", (source, chunk, hash) => {
- const buf = [];
- if(chunk.chunks.length > 0) {
- buf.push("// This file contains only the entry chunk.");
- buf.push("// The chunk loading function for additional chunks");
- buf.push(`${this.requireFn}.e = function requireEnsure(chunkId) {`);
- buf.push(this.indent(this.applyPluginsWaterfall("require-ensure", "throw new Error('Not chunk loading available');", chunk, hash, "chunkId")));
- buf.push("};");
- }
- buf.push("");
- buf.push("// expose the modules object (__webpack_modules__)");
- buf.push(`${this.requireFn}.m = modules;`);
-
- buf.push("");
- buf.push("// expose the module cache");
- buf.push(`${this.requireFn}.c = installedModules;`);
-
- buf.push("");
- buf.push("// define getter function for harmony exports");
- buf.push(`${this.requireFn}.d = function(exports, name, getter) {`);
- buf.push(this.indent([
- `if(!${this.requireFn}.o(exports, name)) {`,
- this.indent([
- "Object.defineProperty(exports, name, {",
- this.indent([
- "configurable: false,",
- "enumerable: true,",
- "get: getter"
- ]),
- "});"
- ]),
- "}"
- ]));
- buf.push("};");
-
- buf.push("");
- buf.push("// getDefaultExport function for compatibility with non-harmony modules");
- buf.push(this.requireFn + ".n = function(module) {");
- buf.push(this.indent([
- "var getter = module && module.__esModule ?",
- this.indent([
- "function getDefault() { return module['default']; } :",
- "function getModuleExports() { return module; };"
- ]),
- `${this.requireFn}.d(getter, 'a', getter);`,
- "return getter;"
- ]));
- buf.push("};");
-
- buf.push("");
- buf.push("// Object.prototype.hasOwnProperty.call");
- buf.push(`${this.requireFn}.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };`);
-
- const publicPath = this.getPublicPath({
- hash: hash
- });
- buf.push("");
- buf.push("// __webpack_public_path__");
- buf.push(`${this.requireFn}.p = ${JSON.stringify(publicPath)};`);
- return this.asString(buf);
- });
-
- this.requireFn = "__webpack_require__";
- }
-
- render(hash, chunk, moduleTemplate, dependencyTemplates) {
- const buf = [];
- buf.push(this.applyPluginsWaterfall("bootstrap", "", chunk, hash, moduleTemplate, dependencyTemplates));
- buf.push(this.applyPluginsWaterfall("local-vars", "", chunk, hash));
- buf.push("");
- buf.push("// The require function");
- buf.push(`function ${this.requireFn}(moduleId) {`);
- buf.push(this.indent(this.applyPluginsWaterfall("require", "", chunk, hash)));
- buf.push("}");
- buf.push("");
- buf.push(this.asString(this.applyPluginsWaterfall("require-extensions", "", chunk, hash)));
- buf.push("");
- buf.push(this.asString(this.applyPluginsWaterfall("startup", "", chunk, hash)));
- let source = this.applyPluginsWaterfall("render", new OriginalSource(this.prefix(buf, " \t") + "\n", `webpack/bootstrap ${hash}`), chunk, hash, moduleTemplate, dependencyTemplates);
- if(chunk.hasEntryModule()) {
- source = this.applyPluginsWaterfall("render-with-entry", source, chunk, hash);
- }
- if(!source) throw new Error("Compiler error: MainTemplate plugin 'render' should return something");
- chunk.rendered = true;
- return new ConcatSource(source, ";");
- }
-
- renderRequireFunctionForModule(hash, chunk, varModuleId) {
- return this.applyPluginsWaterfall("module-require", this.requireFn, chunk, hash, varModuleId);
- }
-
- renderAddModule(hash, chunk, varModuleId, varModule) {
- return this.applyPluginsWaterfall("add-module", `modules[${varModuleId}] = ${varModule};`, chunk, hash, varModuleId, varModule);
- }
-
- renderCurrentHashCode(hash, length) {
- length = length || Infinity;
- return this.applyPluginsWaterfall("current-hash", JSON.stringify(hash.substr(0, length)), length);
- }
-
- entryPointInChildren(chunk) {
- const checkChildren = (chunk, alreadyCheckedChunks) => {
- return chunk.chunks.some((child) => {
- if(alreadyCheckedChunks.indexOf(child) >= 0) return;
- alreadyCheckedChunks.push(child);
- return child.hasEntryModule() || checkChildren(child, alreadyCheckedChunks);
- });
- };
- return checkChildren(chunk, []);
- }
-
- getPublicPath(options) {
- return this.applyPluginsWaterfall("asset-path", this.outputOptions.publicPath || "", options);
- }
-
- updateHash(hash) {
- hash.update("maintemplate");
- hash.update("3");
- hash.update(this.outputOptions.publicPath + "");
- this.applyPlugins("hash", hash);
- }
-
- updateHashForChunk(hash, chunk) {
- this.updateHash(hash);
- this.applyPlugins("hash-for-chunk", hash, chunk);
- }
-
- useChunkHash(chunk) {
- const paths = this.applyPluginsWaterfall("global-hash-paths", []);
- return !this.applyPluginsBailResult("global-hash", chunk, paths);
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const { + ConcatSource, + OriginalSource, + PrefixSource, + RawSource +} = require("webpack-sources"); +const { + Tapable, + SyncWaterfallHook, + SyncHook, + SyncBailHook +} = require("tapable"); +const Template = require("./Template"); + +/** @typedef {import("webpack-sources").ConcatSource} ConcatSource */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("./ModuleTemplate")} ModuleTemplate */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./Module")} Module} */ +/** @typedef {import("./util/createHash").Hash} Hash} */ +/** @typedef {import("./Dependency").DependencyTemplate} DependencyTemplate} */ + +/** + * @typedef {Object} RenderManifestOptions + * @property {Chunk} chunk the chunk used to render + * @property {string} hash + * @property {string} fullHash + * @property {TODO} outputOptions + * @property {{javascript: ModuleTemplate, webassembly: ModuleTemplate}} moduleTemplates + * @property {Map<TODO, TODO>} dependencyTemplates + */ + +// require function shortcuts: +// __webpack_require__.s = the module id of the entry point +// __webpack_require__.c = the module cache +// __webpack_require__.m = the module functions +// __webpack_require__.p = the bundle public path +// __webpack_require__.i = the identity function used for harmony imports +// __webpack_require__.e = the chunk ensure function +// __webpack_require__.d = the exported property define getter function +// __webpack_require__.o = Object.prototype.hasOwnProperty.call +// __webpack_require__.r = define compatibility on export +// __webpack_require__.t = create a fake namespace object +// __webpack_require__.n = compatibility get default export +// __webpack_require__.h = the webpack hash +// __webpack_require__.w = an object containing all installed WebAssembly.Instance export objects keyed by module id +// __webpack_require__.oe = the uncaught error handler for the webpack runtime +// __webpack_require__.nc = the script nonce + +module.exports = class MainTemplate extends Tapable { + /** + * + * @param {TODO=} outputOptions output options for the MainTemplate + */ + constructor(outputOptions) { + super(); + /** @type {TODO?} */ + this.outputOptions = outputOptions || {}; + this.hooks = { + /** @type {SyncWaterfallHook<TODO[], RenderManifestOptions>} */ + renderManifest: new SyncWaterfallHook(["result", "options"]), + modules: new SyncWaterfallHook([ + "modules", + "chunk", + "hash", + "moduleTemplate", + "dependencyTemplates" + ]), + moduleObj: new SyncWaterfallHook([ + "source", + "chunk", + "hash", + "moduleIdExpression" + ]), + requireEnsure: new SyncWaterfallHook([ + "source", + "chunk", + "hash", + "chunkIdExpression" + ]), + bootstrap: new SyncWaterfallHook([ + "source", + "chunk", + "hash", + "moduleTemplate", + "dependencyTemplates" + ]), + localVars: new SyncWaterfallHook(["source", "chunk", "hash"]), + require: new SyncWaterfallHook(["source", "chunk", "hash"]), + requireExtensions: new SyncWaterfallHook(["source", "chunk", "hash"]), + /** @type {SyncWaterfallHook<string, Chunk, string>} */ + beforeStartup: new SyncWaterfallHook(["source", "chunk", "hash"]), + /** @type {SyncWaterfallHook<string, Chunk, string>} */ + startup: new SyncWaterfallHook(["source", "chunk", "hash"]), + render: new SyncWaterfallHook([ + "source", + "chunk", + "hash", + "moduleTemplate", + "dependencyTemplates" + ]), + renderWithEntry: new SyncWaterfallHook(["source", "chunk", "hash"]), + moduleRequire: new SyncWaterfallHook([ + "source", + "chunk", + "hash", + "moduleIdExpression" + ]), + addModule: new SyncWaterfallHook([ + "source", + "chunk", + "hash", + "moduleIdExpression", + "moduleExpression" + ]), + currentHash: new SyncWaterfallHook(["source", "requestedLength"]), + assetPath: new SyncWaterfallHook(["path", "options"]), + hash: new SyncHook(["hash"]), + hashForChunk: new SyncHook(["hash", "chunk"]), + globalHashPaths: new SyncWaterfallHook(["paths"]), + globalHash: new SyncBailHook(["chunk", "paths"]), + + // TODO this should be moved somewhere else + // It's weird here + hotBootstrap: new SyncWaterfallHook(["source", "chunk", "hash"]) + }; + this.hooks.startup.tap("MainTemplate", (source, chunk, hash) => { + /** @type {string[]} */ + const buf = []; + if (chunk.entryModule) { + buf.push("// Load entry module and return exports"); + buf.push( + `return ${this.renderRequireFunctionForModule( + hash, + chunk, + JSON.stringify(chunk.entryModule.id) + )}(${this.requireFn}.s = ${JSON.stringify(chunk.entryModule.id)});` + ); + } + return Template.asString(buf); + }); + this.hooks.render.tap( + "MainTemplate", + (bootstrapSource, chunk, hash, moduleTemplate, dependencyTemplates) => { + const source = new ConcatSource(); + source.add("/******/ (function(modules) { // webpackBootstrap\n"); + source.add(new PrefixSource("/******/", bootstrapSource)); + source.add("/******/ })\n"); + source.add( + "/************************************************************************/\n" + ); + source.add("/******/ ("); + source.add( + this.hooks.modules.call( + new RawSource(""), + chunk, + hash, + moduleTemplate, + dependencyTemplates + ) + ); + source.add(")"); + return source; + } + ); + this.hooks.localVars.tap("MainTemplate", (source, chunk, hash) => { + return Template.asString([ + source, + "// The module cache", + "var installedModules = {};" + ]); + }); + this.hooks.require.tap("MainTemplate", (source, chunk, hash) => { + return Template.asString([ + source, + "// Check if module is in cache", + "if(installedModules[moduleId]) {", + Template.indent("return installedModules[moduleId].exports;"), + "}", + "// Create a new module (and put it into the cache)", + "var module = installedModules[moduleId] = {", + Template.indent(this.hooks.moduleObj.call("", chunk, hash, "moduleId")), + "};", + "", + Template.asString( + outputOptions.strictModuleExceptionHandling + ? [ + "// Execute the module function", + "var threw = true;", + "try {", + Template.indent([ + `modules[moduleId].call(module.exports, module, module.exports, ${this.renderRequireFunctionForModule( + hash, + chunk, + "moduleId" + )});`, + "threw = false;" + ]), + "} finally {", + Template.indent([ + "if(threw) delete installedModules[moduleId];" + ]), + "}" + ] + : [ + "// Execute the module function", + `modules[moduleId].call(module.exports, module, module.exports, ${this.renderRequireFunctionForModule( + hash, + chunk, + "moduleId" + )});` + ] + ), + "", + "// Flag the module as loaded", + "module.l = true;", + "", + "// Return the exports of the module", + "return module.exports;" + ]); + }); + this.hooks.moduleObj.tap( + "MainTemplate", + (source, chunk, hash, varModuleId) => { + return Template.asString(["i: moduleId,", "l: false,", "exports: {}"]); + } + ); + this.hooks.requireExtensions.tap("MainTemplate", (source, chunk, hash) => { + const buf = []; + const chunkMaps = chunk.getChunkMaps(); + // Check if there are non initial chunks which need to be imported using require-ensure + if (Object.keys(chunkMaps.hash).length) { + buf.push("// This file contains only the entry chunk."); + buf.push("// The chunk loading function for additional chunks"); + buf.push(`${this.requireFn}.e = function requireEnsure(chunkId) {`); + buf.push(Template.indent("var promises = [];")); + buf.push( + Template.indent( + this.hooks.requireEnsure.call("", chunk, hash, "chunkId") + ) + ); + buf.push(Template.indent("return Promise.all(promises);")); + buf.push("};"); + } + buf.push(""); + buf.push("// expose the modules object (__webpack_modules__)"); + buf.push(`${this.requireFn}.m = modules;`); + + buf.push(""); + buf.push("// expose the module cache"); + buf.push(`${this.requireFn}.c = installedModules;`); + + buf.push(""); + buf.push("// define getter function for harmony exports"); + buf.push(`${this.requireFn}.d = function(exports, name, getter) {`); + buf.push( + Template.indent([ + `if(!${this.requireFn}.o(exports, name)) {`, + Template.indent([ + "Object.defineProperty(exports, name, { enumerable: true, get: getter });" + ]), + "}" + ]) + ); + buf.push("};"); + + buf.push(""); + buf.push("// define __esModule on exports"); + buf.push(`${this.requireFn}.r = function(exports) {`); + buf.push( + Template.indent([ + "if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {", + Template.indent([ + "Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });" + ]), + "}", + "Object.defineProperty(exports, '__esModule', { value: true });" + ]) + ); + buf.push("};"); + + buf.push(""); + buf.push("// create a fake namespace object"); + buf.push("// mode & 1: value is a module id, require it"); + buf.push("// mode & 2: merge all properties of value into the ns"); + buf.push("// mode & 4: return value when already ns object"); + buf.push("// mode & 8|1: behave like require"); + buf.push(`${this.requireFn}.t = function(value, mode) {`); + buf.push( + Template.indent([ + `if(mode & 1) value = ${this.requireFn}(value);`, + `if(mode & 8) return value;`, + "if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;", + "var ns = Object.create(null);", + `${this.requireFn}.r(ns);`, + "Object.defineProperty(ns, 'default', { enumerable: true, value: value });", + "if(mode & 2 && typeof value != 'string') for(var key in value) " + + `${this.requireFn}.d(ns, key, function(key) { ` + + "return value[key]; " + + "}.bind(null, key));", + "return ns;" + ]) + ); + buf.push("};"); + + buf.push(""); + buf.push( + "// getDefaultExport function for compatibility with non-harmony modules" + ); + buf.push(this.requireFn + ".n = function(module) {"); + buf.push( + Template.indent([ + "var getter = module && module.__esModule ?", + Template.indent([ + "function getDefault() { return module['default']; } :", + "function getModuleExports() { return module; };" + ]), + `${this.requireFn}.d(getter, 'a', getter);`, + "return getter;" + ]) + ); + buf.push("};"); + + buf.push(""); + buf.push("// Object.prototype.hasOwnProperty.call"); + buf.push( + `${ + this.requireFn + }.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };` + ); + + const publicPath = this.getPublicPath({ + hash: hash + }); + buf.push(""); + buf.push("// __webpack_public_path__"); + buf.push(`${this.requireFn}.p = ${JSON.stringify(publicPath)};`); + return Template.asString(buf); + }); + + this.requireFn = "__webpack_require__"; + } + + /** + * + * @param {RenderManifestOptions} options render manifest options + * @returns {TODO[]} returns render manifest + */ + getRenderManifest(options) { + const result = []; + + this.hooks.renderManifest.call(result, options); + + return result; + } + + /** + * TODO webpack 5: remove moduleTemplate and dependencyTemplates + * @param {string} hash hash to be used for render call + * @param {Chunk} chunk Chunk instance + * @param {ModuleTemplate} moduleTemplate ModuleTemplate instance for render + * @param {Map<Function, DependencyTemplate>} dependencyTemplates dependency templates + * @returns {string[]} the generated source of the bootstrap code + */ + renderBootstrap(hash, chunk, moduleTemplate, dependencyTemplates) { + const buf = []; + buf.push( + this.hooks.bootstrap.call( + "", + chunk, + hash, + moduleTemplate, + dependencyTemplates + ) + ); + buf.push(this.hooks.localVars.call("", chunk, hash)); + buf.push(""); + buf.push("// The require function"); + buf.push(`function ${this.requireFn}(moduleId) {`); + buf.push(Template.indent(this.hooks.require.call("", chunk, hash))); + buf.push("}"); + buf.push(""); + buf.push( + Template.asString(this.hooks.requireExtensions.call("", chunk, hash)) + ); + buf.push(""); + buf.push(Template.asString(this.hooks.beforeStartup.call("", chunk, hash))); + buf.push(Template.asString(this.hooks.startup.call("", chunk, hash))); + return buf; + } + + /** + * @param {string} hash hash to be used for render call + * @param {Chunk} chunk Chunk instance + * @param {ModuleTemplate} moduleTemplate ModuleTemplate instance for render + * @param {Map<Function, DependencyTemplate>} dependencyTemplates dependency templates + * @returns {ConcatSource} the newly generated source from rendering + */ + render(hash, chunk, moduleTemplate, dependencyTemplates) { + const buf = this.renderBootstrap( + hash, + chunk, + moduleTemplate, + dependencyTemplates + ); + let source = this.hooks.render.call( + new OriginalSource( + Template.prefix(buf, " \t") + "\n", + "webpack/bootstrap" + ), + chunk, + hash, + moduleTemplate, + dependencyTemplates + ); + if (chunk.hasEntryModule()) { + source = this.hooks.renderWithEntry.call(source, chunk, hash); + } + if (!source) { + throw new Error( + "Compiler error: MainTemplate plugin 'render' should return something" + ); + } + chunk.rendered = true; + return new ConcatSource(source, ";"); + } + + /** + * + * @param {string} hash hash for render fn + * @param {Chunk} chunk Chunk instance for require + * @param {(number|string)=} varModuleId module id + * @returns {TODO} the moduleRequire hook call return signature + */ + renderRequireFunctionForModule(hash, chunk, varModuleId) { + return this.hooks.moduleRequire.call( + this.requireFn, + chunk, + hash, + varModuleId + ); + } + + /** + * + * @param {string} hash hash for render add fn + * @param {Chunk} chunk Chunk instance for require add fn + * @param {(string|number)=} varModuleId module id + * @param {Module} varModule Module instance + * @returns {TODO} renderAddModule call + */ + renderAddModule(hash, chunk, varModuleId, varModule) { + return this.hooks.addModule.call( + `modules[${varModuleId}] = ${varModule};`, + chunk, + hash, + varModuleId, + varModule + ); + } + + /** + * + * @param {string} hash string hash + * @param {number=} length length + * @returns {string} call hook return + */ + renderCurrentHashCode(hash, length) { + length = length || Infinity; + return this.hooks.currentHash.call( + JSON.stringify(hash.substr(0, length)), + length + ); + } + + /** + * + * @param {object} options get public path options + * @returns {string} hook call + */ + getPublicPath(options) { + return this.hooks.assetPath.call( + this.outputOptions.publicPath || "", + options + ); + } + + getAssetPath(path, options) { + return this.hooks.assetPath.call(path, options); + } + + /** + * Updates hash with information from this template + * @param {Hash} hash the hash to update + * @returns {void} + */ + updateHash(hash) { + hash.update("maintemplate"); + hash.update("3"); + this.hooks.hash.call(hash); + } + + /** + * TODO webpack 5: remove moduleTemplate and dependencyTemplates + * Updates hash with chunk-specific information from this template + * @param {Hash} hash the hash to update + * @param {Chunk} chunk the chunk + * @param {ModuleTemplate} moduleTemplate ModuleTemplate instance for render + * @param {Map<Function, DependencyTemplate>} dependencyTemplates dependency templates + * @returns {void} + */ + updateHashForChunk(hash, chunk, moduleTemplate, dependencyTemplates) { + this.updateHash(hash); + this.hooks.hashForChunk.call(hash, chunk); + for (const line of this.renderBootstrap( + "0000", + chunk, + moduleTemplate, + dependencyTemplates + )) { + hash.update(line); + } + } + + useChunkHash(chunk) { + const paths = this.hooks.globalHashPaths.call([]); + return !this.hooks.globalHash.call(chunk, paths); + } +}; diff --git a/node_modules/webpack/lib/MemoryOutputFileSystem.js b/node_modules/webpack/lib/MemoryOutputFileSystem.js index bc0769369..847614888 100644 --- a/node_modules/webpack/lib/MemoryOutputFileSystem.js +++ b/node_modules/webpack/lib/MemoryOutputFileSystem.js @@ -1,5 +1,5 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-module.exports = require("memory-fs");
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +module.exports = require("memory-fs"); diff --git a/node_modules/webpack/lib/Module.js b/node_modules/webpack/lib/Module.js index fb259d863..7685740ab 100644 --- a/node_modules/webpack/lib/Module.js +++ b/node_modules/webpack/lib/Module.js @@ -1,250 +1,431 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const util = require("util");
-
-const DependenciesBlock = require("./DependenciesBlock");
-const ModuleReason = require("./ModuleReason");
-const SortableSet = require("./util/SortableSet");
-const Template = require("./Template");
-
-let debugId = 1000;
-
-const sortById = (a, b) => {
- return a.id - b.id;
-};
-
-const sortByDebugId = (a, b) => {
- return a.debugId - b.debugId;
-};
-
-class Module extends DependenciesBlock {
-
- constructor() {
- super();
- this.context = null;
- this.reasons = [];
- this.debugId = debugId++;
- this.id = null;
- this.portableId = null;
- this.index = null;
- this.index2 = null;
- this.depth = null;
- this.used = null;
- this.usedExports = null;
- this.providedExports = null;
- this._chunks = new SortableSet(undefined, sortById);
- this._chunksDebugIdent = undefined;
- this.warnings = [];
- this.dependenciesWarnings = [];
- this.errors = [];
- this.dependenciesErrors = [];
- this.strict = false;
- this.meta = {};
- this.optimizationBailout = [];
- }
-
- disconnect() {
- this.reasons.length = 0;
- this.id = null;
- this.index = null;
- this.index2 = null;
- this.depth = null;
- this.used = null;
- this.usedExports = null;
- this.providedExports = null;
- this._chunks.clear();
- this._chunksDebugIdent = undefined;
- this.optimizationBailout.length = 0;
- super.disconnect();
- }
-
- unseal() {
- this.id = null;
- this.index = null;
- this.index2 = null;
- this.depth = null;
- this._chunks.clear();
- this._chunksDebugIdent = undefined;
- super.unseal();
- }
-
- setChunks(chunks) {
- this._chunks = new SortableSet(chunks, sortById);
- this._chunksDebugIdent = undefined;
- }
-
- addChunk(chunk) {
- this._chunks.add(chunk);
- this._chunksDebugIdent = undefined;
- }
-
- removeChunk(chunk) {
- if(this._chunks.delete(chunk)) {
- this._chunksDebugIdent = undefined;
- chunk.removeModule(this);
- return true;
- }
- return false;
- }
-
- isInChunk(chunk) {
- return this._chunks.has(chunk);
- }
-
- getChunkIdsIdent() {
- if(this._chunksDebugIdent !== undefined) return this._chunksDebugIdent;
- this._chunks.sortWith(sortByDebugId);
- const chunks = this._chunks;
- const list = [];
- for(const chunk of chunks) {
- const debugId = chunk.debugId;
-
- if(typeof debugId !== "number") {
- return this._chunksDebugIdent = null;
- }
-
- list.push(debugId);
- }
-
- return this._chunksDebugIdent = list.join(",");
- }
-
- forEachChunk(fn) {
- this._chunks.forEach(fn);
- }
-
- mapChunks(fn) {
- return Array.from(this._chunks, fn);
- }
-
- getChunks() {
- return Array.from(this._chunks);
- }
-
- getNumberOfChunks() {
- return this._chunks.size;
- }
-
- hasEqualsChunks(otherModule) {
- if(this._chunks.size !== otherModule._chunks.size) return false;
- this._chunks.sortWith(sortByDebugId);
- otherModule._chunks.sortWith(sortByDebugId);
- const a = this._chunks[Symbol.iterator]();
- const b = otherModule._chunks[Symbol.iterator]();
- while(true) { // eslint-disable-line
- const aItem = a.next();
- const bItem = b.next();
- if(aItem.done) return true;
- if(aItem.value !== bItem.value) return false;
- }
- }
-
- addReason(module, dependency) {
- this.reasons.push(new ModuleReason(module, dependency));
- }
-
- removeReason(module, dependency) {
- for(let i = 0; i < this.reasons.length; i++) {
- let r = this.reasons[i];
- if(r.module === module && r.dependency === dependency) {
- this.reasons.splice(i, 1);
- return true;
- }
- }
- return false;
- }
-
- hasReasonForChunk(chunk) {
- for(let i = 0; i < this.reasons.length; i++) {
- if(this.reasons[i].hasChunk(chunk))
- return true;
- }
- return false;
- }
-
- rewriteChunkInReasons(oldChunk, newChunks) {
- for(let i = 0; i < this.reasons.length; i++) {
- this.reasons[i].rewriteChunks(oldChunk, newChunks);
- }
- }
-
- isUsed(exportName) {
- if(this.used === null) return exportName;
- if(!exportName) return !!this.used;
- if(!this.used) return false;
- if(!this.usedExports) return false;
- if(this.usedExports === true) return exportName;
- let idx = this.usedExports.indexOf(exportName);
- if(idx < 0) return false;
- if(this.isProvided(exportName))
- return Template.numberToIdentifer(idx);
- return exportName;
- }
-
- isProvided(exportName) {
- if(!Array.isArray(this.providedExports))
- return null;
- return this.providedExports.indexOf(exportName) >= 0;
- }
-
- toString() {
- return `Module[${this.id || this.debugId}]`;
- }
-
- needRebuild(fileTimestamps, contextTimestamps) {
- return true;
- }
-
- updateHash(hash) {
- hash.update(this.id + "" + this.used);
- hash.update(JSON.stringify(this.usedExports));
- super.updateHash(hash);
- }
-
- sortItems(sortChunks) {
- super.sortItems();
- if(sortChunks)
- this._chunks.sort();
- this.reasons.sort((a, b) => sortById(a.module, b.module));
- if(Array.isArray(this.usedExports)) {
- this.usedExports.sort();
- }
- }
-
- unbuild() {
- this.disconnect();
- }
-}
-
-Object.defineProperty(Module.prototype, "entry", {
- configurable: false,
- get() {
- throw new Error("Module.entry was removed. Use Chunk.entryModule");
- },
- set() {
- throw new Error("Module.entry was removed. Use Chunk.entryModule");
- }
-});
-
-Object.defineProperty(Module.prototype, "chunks", {
- configurable: false,
- get: util.deprecate(function() {
- return Array.from(this._chunks);
- }, "Module.chunks: Use Module.forEachChunk/mapChunks/getNumberOfChunks/isInChunk/addChunk/removeChunk instead"),
- set() {
- throw new Error("Readonly. Use Module.addChunk/removeChunk to modify chunks.");
- }
-});
-
-Module.prototype.identifier = null;
-Module.prototype.readableIdentifier = null;
-Module.prototype.build = null;
-Module.prototype.source = null;
-Module.prototype.size = null;
-Module.prototype.nameForCondition = null;
-
-module.exports = Module;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const util = require("util"); + +const DependenciesBlock = require("./DependenciesBlock"); +const ModuleReason = require("./ModuleReason"); +const SortableSet = require("./util/SortableSet"); +const Template = require("./Template"); + +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./RequestShortener")} RequestShortener */ +/** @typedef {import("./WebpackError")} WebpackError */ +/** @typedef {import("./util/createHash").Hash} Hash */ + +const EMPTY_RESOLVE_OPTIONS = {}; + +let debugId = 1000; + +const sortById = (a, b) => { + return a.id - b.id; +}; + +const sortByDebugId = (a, b) => { + return a.debugId - b.debugId; +}; + +/** @typedef {(requestShortener: RequestShortener) => string} OptimizationBailoutFunction */ + +class Module extends DependenciesBlock { + constructor(type, context = null) { + super(); + /** @type {string} */ + this.type = type; + /** @type {string} */ + this.context = context; + + // Unique Id + /** @type {number} */ + this.debugId = debugId++; + + // Hash + /** @type {string} */ + this.hash = undefined; + /** @type {string} */ + this.renderedHash = undefined; + + // Info from Factory + /** @type {TODO} */ + this.resolveOptions = EMPTY_RESOLVE_OPTIONS; + /** @type {object} */ + this.factoryMeta = {}; + + // Info from Build + /** @type {WebpackError[]} */ + this.warnings = []; + /** @type {WebpackError[]} */ + this.errors = []; + /** @type {object} */ + this.buildMeta = undefined; + /** @type {object} */ + this.buildInfo = undefined; + + // Graph (per Compilation) + /** @type {ModuleReason[]} */ + this.reasons = []; + /** @type {SortableSet<Chunk>} */ + this._chunks = new SortableSet(undefined, sortById); + + // Info from Compilation (per Compilation) + /** @type {number|string} */ + this.id = null; + /** @type {number} */ + this.index = null; + /** @type {number} */ + this.index2 = null; + /** @type {number} */ + this.depth = null; + /** @type {Module} */ + this.issuer = null; + /** @type {undefined | object} */ + this.profile = undefined; + /** @type {boolean} */ + this.prefetched = false; + /** @type {boolean} */ + this.built = false; + + // Info from Optimization (per Compilation) + /** @type {null | boolean} */ + this.used = null; + /** @type {false | true | string[]} */ + this.usedExports = null; + /** @type {(string | OptimizationBailoutFunction)[]} */ + this.optimizationBailout = []; + + // delayed operations + /** @type {undefined | {oldChunk: Chunk, newChunks: Chunk[]}[] } */ + this._rewriteChunkInReasons = undefined; + + /** @type {boolean} */ + this.useSourceMap = false; + + // info from build + this._source = null; + } + + get exportsArgument() { + return (this.buildInfo && this.buildInfo.exportsArgument) || "exports"; + } + + get moduleArgument() { + return (this.buildInfo && this.buildInfo.moduleArgument) || "module"; + } + + disconnect() { + this.hash = undefined; + this.renderedHash = undefined; + + this.reasons.length = 0; + this._rewriteChunkInReasons = undefined; + this._chunks.clear(); + + this.id = null; + this.index = null; + this.index2 = null; + this.depth = null; + this.issuer = null; + this.profile = undefined; + this.prefetched = false; + this.built = false; + + this.used = null; + this.usedExports = null; + this.optimizationBailout.length = 0; + super.disconnect(); + } + + unseal() { + this.id = null; + this.index = null; + this.index2 = null; + this.depth = null; + this._chunks.clear(); + super.unseal(); + } + + setChunks(chunks) { + this._chunks = new SortableSet(chunks, sortById); + } + + addChunk(chunk) { + if (this._chunks.has(chunk)) return false; + this._chunks.add(chunk); + return true; + } + + removeChunk(chunk) { + if (this._chunks.delete(chunk)) { + chunk.removeModule(this); + return true; + } + return false; + } + + isInChunk(chunk) { + return this._chunks.has(chunk); + } + + isEntryModule() { + for (const chunk of this._chunks) { + if (chunk.entryModule === this) return true; + } + return false; + } + + get optional() { + return ( + this.reasons.length > 0 && + this.reasons.every(r => r.dependency && r.dependency.optional) + ); + } + + /** + * @returns {Chunk[]} all chunks which contain the module + */ + getChunks() { + return Array.from(this._chunks); + } + + getNumberOfChunks() { + return this._chunks.size; + } + + get chunksIterable() { + return this._chunks; + } + + hasEqualsChunks(otherModule) { + if (this._chunks.size !== otherModule._chunks.size) return false; + this._chunks.sortWith(sortByDebugId); + otherModule._chunks.sortWith(sortByDebugId); + const a = this._chunks[Symbol.iterator](); + const b = otherModule._chunks[Symbol.iterator](); + // eslint-disable-next-line no-constant-condition + while (true) { + const aItem = a.next(); + const bItem = b.next(); + if (aItem.done) return true; + if (aItem.value !== bItem.value) return false; + } + } + + addReason(module, dependency, explanation) { + this.reasons.push(new ModuleReason(module, dependency, explanation)); + } + + removeReason(module, dependency) { + for (let i = 0; i < this.reasons.length; i++) { + let r = this.reasons[i]; + if (r.module === module && r.dependency === dependency) { + this.reasons.splice(i, 1); + return true; + } + } + return false; + } + + hasReasonForChunk(chunk) { + if (this._rewriteChunkInReasons) { + for (const operation of this._rewriteChunkInReasons) { + this._doRewriteChunkInReasons(operation.oldChunk, operation.newChunks); + } + this._rewriteChunkInReasons = undefined; + } + for (let i = 0; i < this.reasons.length; i++) { + if (this.reasons[i].hasChunk(chunk)) return true; + } + return false; + } + + hasReasons() { + return this.reasons.length > 0; + } + + rewriteChunkInReasons(oldChunk, newChunks) { + // This is expensive. Delay operation until we really need the data + if (this._rewriteChunkInReasons === undefined) { + this._rewriteChunkInReasons = []; + } + this._rewriteChunkInReasons.push({ + oldChunk, + newChunks + }); + } + + _doRewriteChunkInReasons(oldChunk, newChunks) { + for (let i = 0; i < this.reasons.length; i++) { + this.reasons[i].rewriteChunks(oldChunk, newChunks); + } + } + + isUsed(exportName) { + if (!exportName) return this.used !== false; + if (this.used === null || this.usedExports === null) return exportName; + if (!this.used) return false; + if (!this.usedExports) return false; + if (this.usedExports === true) return exportName; + let idx = this.usedExports.indexOf(exportName); + if (idx < 0) return false; + + // Mangle export name if possible + if (this.isProvided(exportName)) { + if (this.buildMeta.exportsType === "namespace") { + return Template.numberToIdentifer(idx); + } + if ( + this.buildMeta.exportsType === "named" && + !this.usedExports.includes("default") + ) { + return Template.numberToIdentifer(idx); + } + } + return exportName; + } + + isProvided(exportName) { + if (!Array.isArray(this.buildMeta.providedExports)) return null; + return this.buildMeta.providedExports.includes(exportName); + } + + toString() { + return `Module[${this.id || this.debugId}]`; + } + + needRebuild(fileTimestamps, contextTimestamps) { + return true; + } + + /** + * @param {Hash} hash the hash used to track dependencies + * @returns {void} + */ + updateHash(hash) { + hash.update(`${this.id}`); + hash.update(JSON.stringify(this.usedExports)); + super.updateHash(hash); + } + + sortItems(sortChunks) { + super.sortItems(); + if (sortChunks) this._chunks.sort(); + this.reasons.sort((a, b) => { + if (a.module === b.module) return 0; + if (!a.module) return -1; + if (!b.module) return 1; + return sortById(a.module, b.module); + }); + if (Array.isArray(this.usedExports)) { + this.usedExports.sort(); + } + } + + unbuild() { + this.dependencies.length = 0; + this.blocks.length = 0; + this.variables.length = 0; + this.buildMeta = undefined; + this.buildInfo = undefined; + this.disconnect(); + } + + get arguments() { + throw new Error("Module.arguments was removed, there is no replacement."); + } + + set arguments(value) { + throw new Error("Module.arguments was removed, there is no replacement."); + } +} + +// TODO remove in webpack 5 +Object.defineProperty(Module.prototype, "forEachChunk", { + configurable: false, + value: util.deprecate( + /** + * @deprecated + * @param {function(any, any, Set<any>): void} fn callback function + * @returns {void} + * @this {Module} + */ + function(fn) { + this._chunks.forEach(fn); + }, + "Module.forEachChunk: Use for(const chunk of module.chunksIterable) instead" + ) +}); + +// TODO remove in webpack 5 +Object.defineProperty(Module.prototype, "mapChunks", { + configurable: false, + value: util.deprecate( + /** + * @deprecated + * @param {function(any, any): void} fn Mapper function + * @returns {Array<TODO>} Array of chunks mapped + * @this {Module} + */ + function(fn) { + return Array.from(this._chunks, fn); + }, + "Module.mapChunks: Use Array.from(module.chunksIterable, fn) instead" + ) +}); + +// TODO remove in webpack 5 +Object.defineProperty(Module.prototype, "entry", { + configurable: false, + get() { + throw new Error("Module.entry was removed. Use Chunk.entryModule"); + }, + set() { + throw new Error("Module.entry was removed. Use Chunk.entryModule"); + } +}); + +// TODO remove in webpack 5 +Object.defineProperty(Module.prototype, "meta", { + configurable: false, + get: util.deprecate( + /** + * @deprecated + * @returns {void} + * @this {Module} + */ + function() { + return this.buildMeta; + }, + "Module.meta was renamed to Module.buildMeta" + ), + set: util.deprecate( + /** + * @deprecated + * @param {TODO} value Value + * @returns {void} + * @this {Module} + */ + function(value) { + this.buildMeta = value; + }, + "Module.meta was renamed to Module.buildMeta" + ) +}); + +/** @type {function(): string} */ +Module.prototype.identifier = null; + +/** @type {function(RequestShortener): string} */ +Module.prototype.readableIdentifier = null; + +Module.prototype.build = null; +Module.prototype.source = null; +Module.prototype.size = null; +Module.prototype.nameForCondition = null; +/** @type {null | function(Chunk): boolean} */ +Module.prototype.chunkCondition = null; +Module.prototype.updateCacheModule = null; + +module.exports = Module; diff --git a/node_modules/webpack/lib/ModuleBuildError.js b/node_modules/webpack/lib/ModuleBuildError.js index 09158f697..d6b498eef 100644 --- a/node_modules/webpack/lib/ModuleBuildError.js +++ b/node_modules/webpack/lib/ModuleBuildError.js @@ -1,42 +1,52 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const WebpackError = require("./WebpackError");
-const cutOffLoaderExecution = require("./ErrorHelpers").cutOffLoaderExecution;
-
-class ModuleBuildError extends WebpackError {
- constructor(module, err) {
- super();
-
- this.name = "ModuleBuildError";
- this.message = "Module build failed: ";
- if(err !== null && typeof err === "object") {
- if(typeof err.stack === "string" && err.stack) {
- var stack = cutOffLoaderExecution(err.stack);
- if(!err.hideStack) {
- this.message += stack;
- } else {
- this.details = stack;
- if(typeof err.message === "string" && err.message) {
- this.message += err.message;
- } else {
- this.message += err;
- }
- }
- } else if(typeof err.message === "string" && err.message) {
- this.message += err.message;
- } else {
- this.message += err;
- }
- }
- this.module = module;
- this.error = err;
-
- Error.captureStackTrace(this, this.constructor);
- }
-}
-
-module.exports = ModuleBuildError;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const WebpackError = require("./WebpackError"); +const { cutOffLoaderExecution } = require("./ErrorHelpers"); + +class ModuleBuildError extends WebpackError { + constructor(module, err, { from = null } = {}) { + let message = "Module build failed"; + let details = undefined; + if (from) { + message += ` (from ${from}):\n`; + } else { + message += ": "; + } + 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; + if (typeof err.message === "string" && err.message) { + message += err.message; + } else { + message += err; + } + } + } else if (typeof err.message === "string" && err.message) { + message += err.message; + } else { + message += err; + } + } else { + message = err; + } + + super(message); + + this.name = "ModuleBuildError"; + this.details = details; + this.module = module; + this.error = err; + + Error.captureStackTrace(this, this.constructor); + } +} + +module.exports = ModuleBuildError; diff --git a/node_modules/webpack/lib/ModuleDependencyError.js b/node_modules/webpack/lib/ModuleDependencyError.js index 582b6b2ab..cb16cc34a 100644 --- a/node_modules/webpack/lib/ModuleDependencyError.js +++ b/node_modules/webpack/lib/ModuleDependencyError.js @@ -1,22 +1,35 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const WebpackError = require("./WebpackError");
-const formatLocation = require("./formatLocation");
-
-module.exports = class ModuleDependencyError extends WebpackError {
- constructor(module, err, loc) {
- super();
-
- this.name = "ModuleDependencyError";
- this.message = `${formatLocation(loc)} ${err.message}`;
- this.details = err.stack.split("\n").slice(1).join("\n");
- this.origin = this.module = module;
- this.error = err;
-
- Error.captureStackTrace(this, this.constructor);
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const WebpackError = require("./WebpackError"); + +/** @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 {TODO} loc location of dependency + */ + constructor(module, err, loc) { + super(err.message); + + this.name = "ModuleDependencyError"; + this.details = err.stack + .split("\n") + .slice(1) + .join("\n"); + this.module = module; + this.loc = loc; + this.error = err; + this.origin = module.issuer; + + Error.captureStackTrace(this, this.constructor); + } +} + +module.exports = ModuleDependencyError; diff --git a/node_modules/webpack/lib/ModuleDependencyWarning.js b/node_modules/webpack/lib/ModuleDependencyWarning.js index 235fa1bb2..be62791cb 100644 --- a/node_modules/webpack/lib/ModuleDependencyWarning.js +++ b/node_modules/webpack/lib/ModuleDependencyWarning.js @@ -1,22 +1,25 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const WebpackError = require("./WebpackError");
-const formatLocation = require("./formatLocation");
-
-module.exports = class ModuleDependencyWarning extends WebpackError {
- constructor(module, err, loc) {
- super();
-
- this.name = "ModuleDependencyWarning";
- this.message = `${formatLocation(loc)} ${err.message}`;
- this.details = err.stack.split("\n").slice(1).join("\n");
- this.origin = this.module = module;
- this.error = err;
-
- Error.captureStackTrace(this, this.constructor);
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const WebpackError = require("./WebpackError"); + +module.exports = class ModuleDependencyWarning extends WebpackError { + constructor(module, err, loc) { + super(err.message); + + this.name = "ModuleDependencyWarning"; + this.details = err.stack + .split("\n") + .slice(1) + .join("\n"); + this.module = module; + this.loc = loc; + this.error = err; + this.origin = module.issuer; + + Error.captureStackTrace(this, this.constructor); + } +}; diff --git a/node_modules/webpack/lib/ModuleError.js b/node_modules/webpack/lib/ModuleError.js index 9e9be7683..7079d6132 100644 --- a/node_modules/webpack/lib/ModuleError.js +++ b/node_modules/webpack/lib/ModuleError.js @@ -1,24 +1,36 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const WebpackError = require("./WebpackError");
-const cleanUp = require("./ErrorHelpers").cleanUp;
-
-class ModuleError extends WebpackError {
- constructor(module, err) {
- super();
-
- this.name = "ModuleError";
- this.module = module;
- this.message = err && typeof err === "object" && err.message ? err.message : err;
- this.error = err;
- this.details = err && typeof err === "object" && err.stack ? cleanUp(err.stack, this.message) : undefined;
-
- Error.captureStackTrace(this, this.constructor);
- }
-}
-
-module.exports = ModuleError;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const WebpackError = require("./WebpackError"); +const { cleanUp } = require("./ErrorHelpers"); + +class ModuleError extends WebpackError { + constructor(module, err, { from = null } = {}) { + let message = "Module Error"; + if (from) { + message += ` (from ${from}):\n`; + } else { + message += ": "; + } + if (err && typeof err === "object" && err.message) { + message += err.message; + } else if (err) { + message += err; + } + super(message); + this.name = "ModuleError"; + this.module = module; + this.error = err; + this.details = + err && typeof err === "object" && err.stack + ? cleanUp(err.stack, this.message) + : undefined; + + Error.captureStackTrace(this, this.constructor); + } +} + +module.exports = ModuleError; diff --git a/node_modules/webpack/lib/ModuleFilenameHelpers.js b/node_modules/webpack/lib/ModuleFilenameHelpers.js index f61358b07..105e89e3f 100644 --- a/node_modules/webpack/lib/ModuleFilenameHelpers.js +++ b/node_modules/webpack/lib/ModuleFilenameHelpers.js @@ -1,162 +1,178 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const ModuleFilenameHelpers = exports;
-
-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]";
-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;
-
-function getAfter(str, token) {
- const idx = str.indexOf(token);
- return idx < 0 ? "" : str.substr(idx);
-}
-
-function getBefore(str, token) {
- const idx = str.lastIndexOf(token);
- return idx < 0 ? "" : str.substr(0, idx);
-}
-
-function getHash(str) {
- const hash = require("crypto").createHash("md5");
- hash.update(str);
- return hash.digest("hex").substr(0, 4);
-}
-
-function asRegExp(test) {
- if(typeof test === "string") test = new RegExp("^" + test.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"));
- return test;
-}
-
-ModuleFilenameHelpers.createFilename = function createFilename(module, moduleFilenameTemplate, requestShortener) {
- let absoluteResourcePath;
- let hash;
- let identifier;
- let moduleId;
- let shortIdentifier;
- if(module === undefined) module = "";
- if(typeof module === "string") {
- shortIdentifier = requestShortener.shorten(module);
- identifier = shortIdentifier;
- moduleId = "";
- absoluteResourcePath = module.split("!").pop();
- hash = getHash(identifier);
- } else {
- shortIdentifier = module.readableIdentifier(requestShortener);
- identifier = requestShortener.shorten(module.identifier());
- moduleId = module.id;
- absoluteResourcePath = module.identifier().split("!").pop();
- hash = getHash(identifier);
- }
- const resource = shortIdentifier.split("!").pop();
- const loaders = getBefore(shortIdentifier, "!");
- const allLoaders = getBefore(identifier, "!");
- const query = getAfter(resource, "?");
- const resourcePath = resource.substr(0, resource.length - query.length);
- if(typeof moduleFilenameTemplate === "function") {
- return moduleFilenameTemplate({
- identifier: identifier,
- shortIdentifier: shortIdentifier,
- resource: resource,
- resourcePath: resourcePath,
- absoluteResourcePath: absoluteResourcePath,
- allLoaders: allLoaders,
- query: query,
- moduleId: moduleId,
- hash: hash
- });
- }
- return moduleFilenameTemplate
- .replace(ModuleFilenameHelpers.REGEXP_ALL_LOADERS_RESOURCE, identifier)
- .replace(ModuleFilenameHelpers.REGEXP_LOADERS_RESOURCE, shortIdentifier)
- .replace(ModuleFilenameHelpers.REGEXP_RESOURCE, resource)
- .replace(ModuleFilenameHelpers.REGEXP_RESOURCE_PATH, resourcePath)
- .replace(ModuleFilenameHelpers.REGEXP_ABSOLUTE_RESOURCE_PATH, absoluteResourcePath)
- .replace(ModuleFilenameHelpers.REGEXP_ALL_LOADERS, allLoaders)
- .replace(ModuleFilenameHelpers.REGEXP_LOADERS, loaders)
- .replace(ModuleFilenameHelpers.REGEXP_QUERY, query)
- .replace(ModuleFilenameHelpers.REGEXP_ID, moduleId)
- .replace(ModuleFilenameHelpers.REGEXP_HASH, hash);
-};
-
-ModuleFilenameHelpers.createFooter = function createFooter(module, requestShortener) {
- if(!module) module = "";
- if(typeof module === "string") {
- return [
- "// WEBPACK FOOTER //",
- `// ${requestShortener.shorten(module)}`
- ].join("\n");
- } else {
- return [
- "//////////////////",
- "// WEBPACK FOOTER",
- `// ${module.readableIdentifier(requestShortener)}`,
- `// module id = ${module.id}`,
- `// module chunks = ${module.mapChunks(c => c.id).join(" ")}`
- ].join("\n");
- }
-};
-
-ModuleFilenameHelpers.replaceDuplicates = function replaceDuplicates(array, fn, comparator) {
- const countMap = Object.create(null);
- const posMap = Object.create(null);
- array.forEach((item, idx) => {
- countMap[item] = (countMap[item] || []);
- countMap[item].push(idx);
- posMap[item] = 0;
- });
- if(comparator) {
- Object.keys(countMap).forEach(item => {
- 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]++);
- } else return item;
- });
-};
-
-ModuleFilenameHelpers.matchPart = function matchPart(str, test) {
- if(!test) return true;
- test = asRegExp(test);
- if(Array.isArray(test)) {
- return test.map(asRegExp).filter(function(regExp) {
- return regExp.test(str);
- }).length > 0;
- } else {
- return test.test(str);
- }
-};
-
-ModuleFilenameHelpers.matchObject = function matchObject(obj, str) {
- if(obj.test)
- if(!ModuleFilenameHelpers.matchPart(str, obj.test)) return false;
- if(obj.include)
- if(!ModuleFilenameHelpers.matchPart(str, obj.include)) return false;
- if(obj.exclude)
- if(ModuleFilenameHelpers.matchPart(str, obj.exclude)) return false;
- return true;
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const createHash = require("./util/createHash"); + +const ModuleFilenameHelpers = exports; + +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]"; +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; + +const getAfter = (str, token) => { + const idx = str.indexOf(token); + return idx < 0 ? "" : str.substr(idx); +}; + +const getBefore = (str, token) => { + const idx = str.lastIndexOf(token); + return idx < 0 ? "" : str.substr(0, idx); +}; + +const getHash = str => { + const hash = createHash("md4"); + hash.update(str); + return hash.digest("hex").substr(0, 4); +}; + +const asRegExp = test => { + if (typeof test === "string") { + test = new RegExp("^" + test.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")); + } + return test; +}; + +ModuleFilenameHelpers.createFilename = (module, options, requestShortener) => { + const opts = Object.assign( + { + namespace: "", + moduleFilenameTemplate: "" + }, + typeof options === "object" + ? options + : { + moduleFilenameTemplate: options + } + ); + + let absoluteResourcePath; + let hash; + let identifier; + let moduleId; + let shortIdentifier; + if (module === undefined) module = ""; + if (typeof module === "string") { + shortIdentifier = requestShortener.shorten(module); + identifier = shortIdentifier; + moduleId = ""; + absoluteResourcePath = module.split("!").pop(); + hash = getHash(identifier); + } else { + shortIdentifier = module.readableIdentifier(requestShortener); + identifier = requestShortener.shorten(module.identifier()); + moduleId = module.id; + absoluteResourcePath = module + .identifier() + .split("!") + .pop(); + hash = getHash(identifier); + } + const resource = shortIdentifier.split("!").pop(); + const loaders = getBefore(shortIdentifier, "!"); + const allLoaders = getBefore(identifier, "!"); + const query = getAfter(resource, "?"); + const resourcePath = resource.substr(0, resource.length - query.length); + if (typeof opts.moduleFilenameTemplate === "function") { + return opts.moduleFilenameTemplate({ + identifier: identifier, + shortIdentifier: shortIdentifier, + resource: resource, + resourcePath: resourcePath, + absoluteResourcePath: absoluteResourcePath, + allLoaders: allLoaders, + query: query, + moduleId: moduleId, + hash: hash, + namespace: opts.namespace + }); + } + return opts.moduleFilenameTemplate + .replace(ModuleFilenameHelpers.REGEXP_ALL_LOADERS_RESOURCE, identifier) + .replace(ModuleFilenameHelpers.REGEXP_LOADERS_RESOURCE, shortIdentifier) + .replace(ModuleFilenameHelpers.REGEXP_RESOURCE, resource) + .replace(ModuleFilenameHelpers.REGEXP_RESOURCE_PATH, resourcePath) + .replace( + ModuleFilenameHelpers.REGEXP_ABSOLUTE_RESOURCE_PATH, + absoluteResourcePath + ) + .replace(ModuleFilenameHelpers.REGEXP_ALL_LOADERS, allLoaders) + .replace(ModuleFilenameHelpers.REGEXP_LOADERS, loaders) + .replace(ModuleFilenameHelpers.REGEXP_QUERY, query) + .replace(ModuleFilenameHelpers.REGEXP_ID, moduleId) + .replace(ModuleFilenameHelpers.REGEXP_HASH, hash) + .replace(ModuleFilenameHelpers.REGEXP_NAMESPACE, opts.namespace); +}; + +ModuleFilenameHelpers.replaceDuplicates = (array, fn, comparator) => { + const countMap = Object.create(null); + const posMap = Object.create(null); + array.forEach((item, idx) => { + countMap[item] = countMap[item] || []; + countMap[item].push(idx); + posMap[item] = 0; + }); + if (comparator) { + Object.keys(countMap).forEach(item => { + 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]++); + } else { + return item; + } + }); +}; + +ModuleFilenameHelpers.matchPart = (str, test) => { + if (!test) return true; + test = asRegExp(test); + if (Array.isArray(test)) { + return test.map(asRegExp).some(regExp => regExp.test(str)); + } else { + return test.test(str); + } +}; + +ModuleFilenameHelpers.matchObject = (obj, str) => { + if (obj.test) { + if (!ModuleFilenameHelpers.matchPart(str, obj.test)) { + return false; + } + } + if (obj.include) { + if (!ModuleFilenameHelpers.matchPart(str, obj.include)) { + return false; + } + } + if (obj.exclude) { + if (ModuleFilenameHelpers.matchPart(str, obj.exclude)) { + return false; + } + } + return true; +}; diff --git a/node_modules/webpack/lib/ModuleNotFoundError.js b/node_modules/webpack/lib/ModuleNotFoundError.js index 454cd48bf..cdfc3147b 100644 --- a/node_modules/webpack/lib/ModuleNotFoundError.js +++ b/node_modules/webpack/lib/ModuleNotFoundError.js @@ -1,26 +1,23 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const WebpackError = require("./WebpackError");
-
-class ModuleNotFoundError extends WebpackError {
- constructor(module, err, dependencies) {
- super();
-
- this.name = "ModuleNotFoundError";
- this.message = "Module not found: " + err;
- this.details = err.details;
- this.missing = err.missing;
- this.module = module;
- this.origin = module;
- this.dependencies = dependencies;
- this.error = err;
-
- Error.captureStackTrace(this, this.constructor);
- }
-}
-
-module.exports = ModuleNotFoundError;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const WebpackError = require("./WebpackError"); + +class ModuleNotFoundError extends WebpackError { + constructor(module, err) { + super("Module not found: " + err); + + this.name = "ModuleNotFoundError"; + this.details = err.details; + this.missing = err.missing; + this.module = module; + this.error = err; + + Error.captureStackTrace(this, this.constructor); + } +} + +module.exports = ModuleNotFoundError; diff --git a/node_modules/webpack/lib/ModuleParseError.js b/node_modules/webpack/lib/ModuleParseError.js index 3431d477b..32c7a69c1 100644 --- a/node_modules/webpack/lib/ModuleParseError.js +++ b/node_modules/webpack/lib/ModuleParseError.js @@ -1,34 +1,57 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const WebpackError = require("./WebpackError");
-
-class ModuleParseError extends WebpackError {
- constructor(module, source, err) {
- super();
-
- this.name = "ModuleParseError";
- this.message = "Module parse failed: " + err.message;
- this.message += "\nYou may need an appropriate loader to handle this file type.";
- if(err.loc && typeof err.loc === "object" && typeof err.loc.line === "number") {
- var lineNumber = err.loc.line;
- if(/[\0\u0001\u0002\u0003\u0004\u0005\u0006\u0007]/.test(source)) { // binary file
- this.message += "\n(Source code omitted for this binary file)";
- } else {
- source = source.split("\n");
- this.message += "\n| " + source.slice(Math.max(0, lineNumber - 3), lineNumber + 2).join("\n| ");
- }
- } else {
- this.message += "\n" + err.stack;
- }
- this.module = module;
- this.error = err;
-
- Error.captureStackTrace(this, this.constructor);
- }
-}
-
-module.exports = ModuleParseError;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const WebpackError = require("./WebpackError"); + +/** @typedef {import("./Module")} Module */ + +class ModuleParseError extends WebpackError { + /** + * @param {Module} module the errored module + * @param {string} source source code + * @param {Error&any} err the parse error + */ + constructor(module, source, err) { + let message = "Module parse failed: " + err.message; + let loc = undefined; + message += "\nYou may need an appropriate loader to handle this file type."; + if ( + err.loc && + typeof err.loc === "object" && + typeof err.loc.line === "number" + ) { + var lineNumber = err.loc.line; + if (/[\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("\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 = err.loc; + } else { + message += "\n" + err.stack; + } + + super(message); + + this.name = "ModuleParseError"; + this.module = module; + this.loc = loc; + this.error = err; + + Error.captureStackTrace(this, this.constructor); + } +} + +module.exports = ModuleParseError; diff --git a/node_modules/webpack/lib/ModuleReason.js b/node_modules/webpack/lib/ModuleReason.js index 52f539d01..3697f8495 100644 --- a/node_modules/webpack/lib/ModuleReason.js +++ b/node_modules/webpack/lib/ModuleReason.js @@ -1,50 +1,48 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const util = require("util");
-
-class ModuleReason {
- constructor(module, dependency) {
- this.module = module;
- this.dependency = dependency;
- this._chunks = null;
- }
-
- hasChunk(chunk) {
- if(this._chunks) {
- if(this._chunks.has(chunk))
- return true;
- } else if(this.module._chunks.has(chunk))
- return true;
- return false;
- }
-
- rewriteChunks(oldChunk, newChunks) {
- if(!this._chunks) {
- if(!this.module._chunks.has(oldChunk))
- return;
- this._chunks = new Set(this.module._chunks);
- }
- if(this._chunks.has(oldChunk)) {
- this._chunks.delete(oldChunk);
- for(let i = 0; i < newChunks.length; i++) {
- this._chunks.add(newChunks[i]);
- }
- }
- }
-}
-
-Object.defineProperty(ModuleReason.prototype, "chunks", {
- configurable: false,
- get: util.deprecate(function() {
- return this._chunks ? Array.from(this._chunks) : null;
- }, "ModuleReason.chunks: Use ModuleReason.hasChunk/rewriteChunks instead"),
- set() {
- throw new Error("Readonly. Use ModuleReason.rewriteChunks to modify chunks.");
- }
-});
-
-module.exports = ModuleReason;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./Dependency")} Dependency */ + +class ModuleReason { + /** + * @param {Module} module the referencing module + * @param {Dependency} dependency the referencing dependency + * @param {string=} explanation some extra detail + */ + constructor(module, dependency, explanation) { + this.module = module; + this.dependency = dependency; + this.explanation = explanation; + this._chunks = null; + } + + hasChunk(chunk) { + if (this._chunks) { + if (this._chunks.has(chunk)) return true; + } else if (this.module && this.module._chunks.has(chunk)) return true; + return false; + } + + rewriteChunks(oldChunk, newChunks) { + if (!this._chunks) { + if (this.module) { + if (!this.module._chunks.has(oldChunk)) return; + this._chunks = new Set(this.module._chunks); + } else { + this._chunks = new Set(); + } + } + if (this._chunks.has(oldChunk)) { + this._chunks.delete(oldChunk); + for (let i = 0; i < newChunks.length; i++) { + this._chunks.add(newChunks[i]); + } + } + } +} + +module.exports = ModuleReason; diff --git a/node_modules/webpack/lib/ModuleTemplate.js b/node_modules/webpack/lib/ModuleTemplate.js index 69834df48..06e787ed9 100644 --- a/node_modules/webpack/lib/ModuleTemplate.js +++ b/node_modules/webpack/lib/ModuleTemplate.js @@ -1,23 +1,93 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const Template = require("./Template");
-
-module.exports = class ModuleTemplate extends Template {
- constructor(outputOptions) {
- super(outputOptions);
- }
- render(module, dependencyTemplates, chunk) {
- const moduleSource = module.source(dependencyTemplates, this.outputOptions, this.requestShortener);
- const moduleSourcePostModule = this.applyPluginsWaterfall("module", moduleSource, module, chunk, dependencyTemplates);
- const moduleSourcePostRender = this.applyPluginsWaterfall("render", moduleSourcePostModule, module, chunk, dependencyTemplates);
- return this.applyPluginsWaterfall("package", moduleSourcePostRender, module, chunk, dependencyTemplates);
- }
- updateHash(hash) {
- hash.update("1");
- this.applyPlugins("hash", hash);
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const { Tapable, SyncWaterfallHook, SyncHook } = require("tapable"); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("./Module")} Module */ + +module.exports = class ModuleTemplate extends Tapable { + constructor(runtimeTemplate, type) { + super(); + this.runtimeTemplate = runtimeTemplate; + this.type = type; + this.hooks = { + content: new SyncWaterfallHook([ + "source", + "module", + "options", + "dependencyTemplates" + ]), + module: new SyncWaterfallHook([ + "source", + "module", + "options", + "dependencyTemplates" + ]), + render: new SyncWaterfallHook([ + "source", + "module", + "options", + "dependencyTemplates" + ]), + package: new SyncWaterfallHook([ + "source", + "module", + "options", + "dependencyTemplates" + ]), + hash: new SyncHook(["hash"]) + }; + } + + /** + * @param {Module} module the module + * @param {TODO} dependencyTemplates templates for dependencies + * @param {TODO} options render options + * @returns {Source} the source + */ + render(module, dependencyTemplates, options) { + try { + const moduleSource = module.source( + dependencyTemplates, + this.runtimeTemplate, + this.type + ); + const moduleSourcePostContent = this.hooks.content.call( + moduleSource, + module, + options, + dependencyTemplates + ); + const moduleSourcePostModule = this.hooks.module.call( + moduleSourcePostContent, + module, + options, + dependencyTemplates + ); + const moduleSourcePostRender = this.hooks.render.call( + moduleSourcePostModule, + module, + options, + dependencyTemplates + ); + return this.hooks.package.call( + moduleSourcePostRender, + module, + options, + dependencyTemplates + ); + } catch (e) { + e.message = `${module.identifier()}\n${e.message}`; + throw e; + } + } + + updateHash(hash) { + hash.update("1"); + this.hooks.hash.call(hash); + } +}; diff --git a/node_modules/webpack/lib/ModuleWarning.js b/node_modules/webpack/lib/ModuleWarning.js index 2bda197a6..13068192c 100644 --- a/node_modules/webpack/lib/ModuleWarning.js +++ b/node_modules/webpack/lib/ModuleWarning.js @@ -1,24 +1,36 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const WebpackError = require("./WebpackError");
-const cleanUp = require("./ErrorHelpers").cleanUp;
-
-class ModuleWarning extends WebpackError {
- constructor(module, warning) {
- super();
-
- this.name = "ModuleWarning";
- this.module = module;
- this.message = warning && typeof warning === "object" && warning.message ? warning.message : warning;
- this.warning = warning;
- this.details = warning && typeof warning === "object" && warning.stack ? cleanUp(warning.stack, this.message) : undefined;
-
- Error.captureStackTrace(this, this.constructor);
- }
-}
-
-module.exports = ModuleWarning;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const WebpackError = require("./WebpackError"); +const { cleanUp } = require("./ErrorHelpers"); + +class ModuleWarning extends WebpackError { + constructor(module, warning, { from = null } = {}) { + let message = "Module Warning"; + if (from) { + message += ` (from ${from}):\n`; + } else { + message += ": "; + } + if (warning && typeof warning === "object" && warning.message) { + message += warning.message; + } else if (warning) { + message += warning; + } + super(message); + this.name = "ModuleWarning"; + this.module = module; + this.warning = warning; + this.details = + warning && typeof warning === "object" && warning.stack + ? cleanUp(warning.stack, this.message) + : undefined; + + Error.captureStackTrace(this, this.constructor); + } +} + +module.exports = ModuleWarning; diff --git a/node_modules/webpack/lib/MovedToPluginWarningPlugin.js b/node_modules/webpack/lib/MovedToPluginWarningPlugin.js deleted file mode 100644 index e4198d1ca..000000000 --- a/node_modules/webpack/lib/MovedToPluginWarningPlugin.js +++ /dev/null @@ -1,21 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-module.exports = class MovedToPluginWarningPlugin {
- constructor(optionName, pluginName) {
- this.optionName = optionName;
- this.pluginName = pluginName;
- }
- apply(compiler) {
- const optionName = this.optionName;
- const pluginName = this.pluginName;
- compiler.plugin("compilation", (compilation) => {
- compilation.warnings.push(new Error `webpack options:
- DEPRECATED option ${optionName} will be moved to the ${pluginName}.
- Use this instead.
- For more info about the usage of the ${pluginName} see https://webpack.js.org/plugins/`);
- });
- }
-};
diff --git a/node_modules/webpack/lib/MultiCompiler.js b/node_modules/webpack/lib/MultiCompiler.js index 8c9b8c183..cdc7fb508 100644 --- a/node_modules/webpack/lib/MultiCompiler.js +++ b/node_modules/webpack/lib/MultiCompiler.js @@ -1,164 +1,283 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const Tapable = require("tapable");
-const asyncLib = require("async");
-const MultiWatching = require("./MultiWatching");
-const MultiStats = require("./MultiStats");
-
-module.exports = class MultiCompiler extends Tapable {
- constructor(compilers) {
- super();
- if(!Array.isArray(compilers)) {
- compilers = Object.keys(compilers).map((name) => {
- compilers[name].name = name;
- return compilers[name];
- });
- }
- this.compilers = compilers;
- let doneCompilers = 0;
- let compilerStats = [];
- this.compilers.forEach((compiler, idx) => {
- let compilerDone = false;
- compiler.plugin("done", stats => {
- if(!compilerDone) {
- compilerDone = true;
- doneCompilers++;
- }
- compilerStats[idx] = stats;
- if(doneCompilers === this.compilers.length) {
- this.applyPlugins("done", new MultiStats(compilerStats));
- }
- });
- compiler.plugin("invalid", () => {
- if(compilerDone) {
- compilerDone = false;
- doneCompilers--;
- }
- this.applyPlugins("invalid");
- });
- }, this);
- }
-
- 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");
- }
-
- get outputFileSystem() {
- throw new Error("Cannot read outputFileSystem of a MultiCompiler");
- }
-
- set inputFileSystem(value) {
- this.compilers.forEach(compiler => {
- compiler.inputFileSystem = value;
- });
- }
-
- set outputFileSystem(value) {
- this.compilers.forEach(compiler => {
- compiler.outputFileSystem = value;
- });
- }
-
- runWithDependencies(compilers, fn, callback) {
- let fulfilledNames = {};
- let remainingCompilers = compilers;
- const isDependencyFulfilled = (d) => fulfilledNames[d];
- const getReadyCompilers = () => {
- let readyCompilers = [];
- let list = remainingCompilers;
- remainingCompilers = [];
- for(const c of list) {
- const ready = !c.dependencies || c.dependencies.every(isDependencyFulfilled);
- if(ready)
- readyCompilers.push(c);
- else
- remainingCompilers.push(c);
- }
- return readyCompilers;
- };
- const runCompilers = (callback) => {
- if(remainingCompilers.length === 0) return callback();
- asyncLib.map(getReadyCompilers(), (compiler, callback) => {
- fn(compiler, (err) => {
- if(err) return callback(err);
- fulfilledNames[compiler.name] = true;
- runCompilers(callback);
- });
- }, callback);
- };
- runCompilers(callback);
- }
-
- watch(watchOptions, handler) {
- let watchings = [];
- let allStats = this.compilers.map(() => null);
- let compilerStatus = this.compilers.map(() => false);
- this.runWithDependencies(this.compilers, (compiler, callback) => {
- const compilerIdx = this.compilers.indexOf(compiler);
- let firstRun = true;
- let watching = compiler.watch(Array.isArray(watchOptions) ? watchOptions[compilerIdx] : watchOptions, (err, stats) => {
- if(err)
- handler(err);
- if(stats) {
- allStats[compilerIdx] = stats;
- compilerStatus[compilerIdx] = "new";
- if(compilerStatus.every(Boolean)) {
- const freshStats = allStats.filter((s, idx) => {
- return compilerStatus[idx] === "new";
- });
- compilerStatus.fill(true);
- const multiStats = new MultiStats(freshStats);
- handler(null, multiStats);
- }
- }
- if(firstRun && !err) {
- firstRun = false;
- callback();
- }
- });
- watchings.push(watching);
- }, () => {
- // ignore
- });
-
- return new MultiWatching(watchings, this);
- }
-
- run(callback) {
- const allStats = this.compilers.map(() => null);
- this.runWithDependencies(this.compilers, ((compiler, callback) => {
- const compilerIdx = this.compilers.indexOf(compiler);
- compiler.run((err, stats) => {
- if(err) return callback(err);
- allStats[compilerIdx] = stats;
- callback();
- });
- }), (err) => {
- if(err) return callback(err);
- callback(null, new MultiStats(allStats));
- });
- }
-
- purgeInputFileSystem() {
- this.compilers.forEach((compiler) => {
- if(compiler.inputFileSystem && compiler.inputFileSystem.purge)
- compiler.inputFileSystem.purge();
- });
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const { Tapable, SyncHook, MultiHook } = require("tapable"); +const asyncLib = require("neo-async"); +const MultiWatching = require("./MultiWatching"); +const MultiStats = require("./MultiStats"); +const ConcurrentCompilationError = require("./ConcurrentCompilationError"); + +module.exports = class MultiCompiler extends Tapable { + constructor(compilers) { + super(); + this.hooks = { + done: new SyncHook(["stats"]), + invalid: new MultiHook(compilers.map(c => c.hooks.invalid)), + run: new MultiHook(compilers.map(c => c.hooks.run)), + watchClose: new SyncHook([]), + watchRun: new MultiHook(compilers.map(c => c.hooks.watchRun)) + }; + if (!Array.isArray(compilers)) { + compilers = Object.keys(compilers).map(name => { + compilers[name].name = name; + return compilers[name]; + }); + } + this.compilers = compilers; + let doneCompilers = 0; + let compilerStats = []; + let index = 0; + for (const compiler of this.compilers) { + let compilerDone = false; + const compilerIndex = index++; + // 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(compilerStats)); + } + }); + // eslint-disable-next-line no-loop-func + compiler.hooks.invalid.tap("MultiCompiler", () => { + if (compilerDone) { + compilerDone = false; + doneCompilers--; + } + }); + } + this.running = false; + } + + 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"); + } + + get outputFileSystem() { + throw new Error("Cannot read outputFileSystem of a MultiCompiler"); + } + + set inputFileSystem(value) { + for (const compiler of this.compilers) { + compiler.inputFileSystem = value; + } + } + + set outputFileSystem(value) { + for (const compiler of this.compilers) { + compiler.outputFileSystem = value; + } + } + + validateDependencies(callback) { + const edges = new Set(); + const missing = []; + const targetFound = compiler => { + for (const edge of edges) { + if (edge.target === compiler) { + return true; + } + } + return false; + }; + const sortEdges = (e1, e2) => { + return ( + e1.source.name.localeCompare(e2.source.name) || + e1.target.name.localeCompare(e2.target.name) + ); + }; + for (const source of this.compilers) { + if (source.dependencies) { + for (const dep of source.dependencies) { + const target = this.compilers.find(c => c.name === dep); + if (!target) { + missing.push(dep); + } else { + edges.add({ + source, + target + }); + } + } + } + } + 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) { + 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; + } + + runWithDependencies(compilers, fn, callback) { + const fulfilledNames = new Set(); + let remainingCompilers = compilers; + const isDependencyFulfilled = d => fulfilledNames.has(d); + const getReadyCompilers = () => { + let readyCompilers = []; + let list = remainingCompilers; + remainingCompilers = []; + for (const c of list) { + const ready = + !c.dependencies || c.dependencies.every(isDependencyFulfilled); + if (ready) { + readyCompilers.push(c); + } else { + remainingCompilers.push(c); + } + } + return readyCompilers; + }; + const runCompilers = callback => { + if (remainingCompilers.length === 0) return callback(); + asyncLib.map( + getReadyCompilers(), + (compiler, callback) => { + fn(compiler, err => { + if (err) return callback(err); + fulfilledNames.add(compiler.name); + runCompilers(callback); + }); + }, + callback + ); + }; + runCompilers(callback); + } + + watch(watchOptions, handler) { + if (this.running) return handler(new ConcurrentCompilationError()); + + let watchings = []; + let allStats = this.compilers.map(() => null); + let compilerStatus = this.compilers.map(() => false); + if (this.validateDependencies(handler)) { + this.running = true; + this.runWithDependencies( + this.compilers, + (compiler, callback) => { + const compilerIdx = this.compilers.indexOf(compiler); + let firstRun = true; + let watching = compiler.watch( + Array.isArray(watchOptions) + ? watchOptions[compilerIdx] + : watchOptions, + (err, stats) => { + if (err) handler(err); + if (stats) { + allStats[compilerIdx] = stats; + compilerStatus[compilerIdx] = "new"; + if (compilerStatus.every(Boolean)) { + const freshStats = allStats.filter((s, idx) => { + return compilerStatus[idx] === "new"; + }); + compilerStatus.fill(true); + const multiStats = new MultiStats(freshStats); + handler(null, multiStats); + } + } + if (firstRun && !err) { + firstRun = false; + callback(); + } + } + ); + watchings.push(watching); + }, + () => { + // ignore + } + ); + } + + return new MultiWatching(watchings, this); + } + + run(callback) { + if (this.running) { + return callback(new ConcurrentCompilationError()); + } + + const finalCallback = (err, stats) => { + this.running = false; + + if (callback !== undefined) { + return callback(err, stats); + } + }; + + const allStats = this.compilers.map(() => null); + if (this.validateDependencies(callback)) { + this.running = true; + this.runWithDependencies( + this.compilers, + (compiler, callback) => { + const compilerIdx = this.compilers.indexOf(compiler); + compiler.run((err, stats) => { + if (err) { + return callback(err); + } + allStats[compilerIdx] = stats; + callback(); + }); + }, + err => { + if (err) { + return finalCallback(err); + } + finalCallback(null, new MultiStats(allStats)); + } + ); + } + } + + purgeInputFileSystem() { + for (const compiler of this.compilers) { + if (compiler.inputFileSystem && compiler.inputFileSystem.purge) { + compiler.inputFileSystem.purge(); + } + } + } +}; diff --git a/node_modules/webpack/lib/MultiEntryPlugin.js b/node_modules/webpack/lib/MultiEntryPlugin.js index e7ca65189..b38a82399 100644 --- a/node_modules/webpack/lib/MultiEntryPlugin.js +++ b/node_modules/webpack/lib/MultiEntryPlugin.js @@ -1,39 +1,80 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const MultiEntryDependency = require("./dependencies/MultiEntryDependency");
-const SingleEntryDependency = require("./dependencies/SingleEntryDependency");
-const MultiModuleFactory = require("./MultiModuleFactory");
-
-module.exports = class MultiEntryPlugin {
- constructor(context, entries, name) {
- this.context = context;
- this.entries = entries;
- this.name = name;
- }
-
- apply(compiler) {
- compiler.plugin("compilation", (compilation, params) => {
- const multiModuleFactory = new MultiModuleFactory();
- const normalModuleFactory = params.normalModuleFactory;
-
- compilation.dependencyFactories.set(MultiEntryDependency, multiModuleFactory);
- compilation.dependencyFactories.set(SingleEntryDependency, normalModuleFactory);
- });
- compiler.plugin("make", (compilation, callback) => {
- const dep = MultiEntryPlugin.createDependency(this.entries, this.name);
- compilation.addEntry(this.context, dep, this.name, callback);
- });
- }
-
- static createDependency(entries, name) {
- return new MultiEntryDependency(entries.map((e, idx) => {
- const dep = new SingleEntryDependency(e);
- dep.loc = name + ":" + (100000 + idx);
- return dep;
- }), name);
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const MultiEntryDependency = require("./dependencies/MultiEntryDependency"); +const SingleEntryDependency = require("./dependencies/SingleEntryDependency"); +const MultiModuleFactory = require("./MultiModuleFactory"); + +/** @typedef {import("./Compiler")} Compiler */ + +class MultiEntryPlugin { + /** + * The MultiEntryPlugin is invoked whenever this.options.entry value is an array of paths + * @param {string} context context path + * @param {string[]} entries array of entry paths + * @param {string} name entry key name + */ + constructor(context, entries, name) { + this.context = context; + this.entries = entries; + this.name = name; + } + + /** + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "MultiEntryPlugin", + (compilation, { normalModuleFactory }) => { + const multiModuleFactory = new MultiModuleFactory(); + + compilation.dependencyFactories.set( + MultiEntryDependency, + multiModuleFactory + ); + compilation.dependencyFactories.set( + SingleEntryDependency, + normalModuleFactory + ); + } + ); + + compiler.hooks.make.tapAsync( + "MultiEntryPlugin", + (compilation, callback) => { + const { context, entries, name } = this; + + const dep = MultiEntryPlugin.createDependency(entries, name); + compilation.addEntry(context, dep, name, callback); + } + ); + } + + /** + * @param {string[]} entries each entry path string + * @param {string} name name of the entry + * @returns {MultiEntryDependency} returns a constructed Dependency + */ + static createDependency(entries, name) { + return new MultiEntryDependency( + entries.map((e, idx) => { + const dep = new SingleEntryDependency(e); + // Because entrypoints are not dependencies found in an + // existing module, we give it a synthetic id + dep.loc = { + name, + index: idx + }; + return dep; + }), + name + ); + } +} + +module.exports = MultiEntryPlugin; diff --git a/node_modules/webpack/lib/MultiModule.js b/node_modules/webpack/lib/MultiModule.js index b6a91e34f..c8e5d5757 100644 --- a/node_modules/webpack/lib/MultiModule.js +++ b/node_modules/webpack/lib/MultiModule.js @@ -1,75 +1,87 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const Module = require("./Module");
-const RawSource = require("webpack-sources").RawSource;
-
-class MultiModule extends Module {
-
- constructor(context, dependencies, name) {
- super();
- this.context = context;
- this.dependencies = dependencies;
- this.name = name;
- this.built = false;
- this.cacheable = true;
- }
-
- identifier() {
- return `multi ${this.dependencies.map((d) => d.request).join(" ")}`;
- }
-
- readableIdentifier(requestShortener) {
- return `multi ${this.dependencies.map((d) => requestShortener.shorten(d.request)).join(" ")}`;
- }
-
- disconnect() {
- this.built = false;
- super.disconnect();
- }
-
- build(options, compilation, resolver, fs, callback) {
- this.built = true;
- return callback();
- }
-
- needRebuild() {
- return false;
- }
-
- size() {
- return 16 + this.dependencies.length * 12;
- }
-
- updateHash(hash) {
- hash.update("multi module");
- hash.update(this.name || "");
- super.updateHash(hash);
- }
-
- source(dependencyTemplates, outputOptions) {
- const str = [];
- this.dependencies.forEach(function(dep, idx) {
- if(dep.module) {
- if(idx === this.dependencies.length - 1)
- str.push("module.exports = ");
- str.push("__webpack_require__(");
- if(outputOptions.pathinfo)
- str.push(`/*! ${dep.request} */`);
- str.push(`${JSON.stringify(dep.module.id)}`);
- str.push(")");
- } else {
- str.push("(function webpackMissingModule() { throw new Error(");
- str.push(JSON.stringify(`Cannot find module "${dep.request}"`));
- str.push("); }())");
- }
- str.push(";\n");
- }, this);
- return new RawSource(str.join(""));
- }
-}
-
-module.exports = MultiModule;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Module = require("./Module"); +const Template = require("./Template"); +const { RawSource } = require("webpack-sources"); + +/** @typedef {import("./util/createHash").Hash} Hash */ + +class MultiModule extends Module { + constructor(context, dependencies, name) { + super("javascript/dynamic", context); + + // Info from Factory + this.dependencies = dependencies; + this.name = name; + this._identifier = `multi ${this.dependencies + .map(d => d.request) + .join(" ")}`; + } + + identifier() { + return this._identifier; + } + + readableIdentifier(requestShortener) { + return `multi ${this.dependencies + .map(d => requestShortener.shorten(d.request)) + .join(" ")}`; + } + + build(options, compilation, resolver, fs, callback) { + this.built = true; + this.buildMeta = {}; + this.buildInfo = {}; + return callback(); + } + + needRebuild() { + return false; + } + + size() { + return 16 + this.dependencies.length * 12; + } + + /** + * @param {Hash} hash the hash used to track dependencies + * @returns {void} + */ + updateHash(hash) { + hash.update("multi module"); + hash.update(this.name || ""); + super.updateHash(hash); + } + + source(dependencyTemplates, runtimeTemplate) { + const str = []; + let idx = 0; + for (const dep of this.dependencies) { + if (dep.module) { + if (idx === this.dependencies.length - 1) { + str.push("module.exports = "); + } + str.push("__webpack_require__("); + if (runtimeTemplate.outputOptions.pathinfo) { + str.push(Template.toComment(dep.request)); + } + str.push(`${JSON.stringify(dep.module.id)}`); + str.push(")"); + } else { + const content = require("./dependencies/WebpackMissingModule").module( + dep.request + ); + str.push(content); + } + str.push(";\n"); + idx++; + } + return new RawSource(str.join("")); + } +} + +module.exports = MultiModule; diff --git a/node_modules/webpack/lib/MultiModuleFactory.js b/node_modules/webpack/lib/MultiModuleFactory.js index d28bfb551..5d29b2056 100644 --- a/node_modules/webpack/lib/MultiModuleFactory.js +++ b/node_modules/webpack/lib/MultiModuleFactory.js @@ -1,19 +1,23 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const Tapable = require("tapable");
-const MultiModule = require("./MultiModule");
-
-module.exports = class MultiModuleFactory extends Tapable {
- constructor() {
- super();
- }
-
- create(data, callback) {
- const dependency = data.dependencies[0];
- callback(null, new MultiModule(data.context, dependency.dependencies, dependency.name));
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const { Tapable } = require("tapable"); +const MultiModule = require("./MultiModule"); + +module.exports = class MultiModuleFactory extends Tapable { + constructor() { + super(); + this.hooks = {}; + } + + create(data, callback) { + const dependency = data.dependencies[0]; + callback( + null, + new MultiModule(data.context, dependency.dependencies, dependency.name) + ); + } +}; diff --git a/node_modules/webpack/lib/MultiStats.js b/node_modules/webpack/lib/MultiStats.js index 3401c9d30..1a5fcf2b0 100644 --- a/node_modules/webpack/lib/MultiStats.js +++ b/node_modules/webpack/lib/MultiStats.js @@ -1,79 +1,92 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const Stats = require("./Stats");
-
-const optionOrFallback = (optionValue, fallbackValue) => optionValue !== undefined ? optionValue : fallbackValue;
-
-class MultiStats {
- constructor(stats) {
- this.stats = stats;
- this.hash = stats.map(stat => stat.hash).join("");
- }
-
- hasErrors() {
- return this.stats.map((stat) => stat.hasErrors()).reduce((a, b) => a || b, false);
- }
-
- hasWarnings() {
- return this.stats.map((stat) => stat.hasWarnings()).reduce((a, b) => a || b, false);
- }
-
- toJson(options, forToString) {
- if(typeof options === "boolean" || typeof options === "string") {
- options = Stats.presetToOptions(options);
- } else if(!options) {
- options = {};
- }
- const jsons = this.stats.map((stat, idx) => {
- const childOptions = Stats.getChildOptions(options, idx);
- const obj = stat.toJson(childOptions, forToString);
- obj.name = stat.compilation && stat.compilation.name;
- return obj;
- });
- const showVersion = typeof options.version === "undefined" ? jsons.every(j => j.version) : options.version !== false;
- const showHash = typeof options.hash === "undefined" ? jsons.every(j => j.hash) : options.hash !== false;
- jsons.forEach(j => {
- if(showVersion)
- delete j.version;
- });
- const obj = {
- errors: jsons.reduce((arr, j) => {
- return arr.concat(j.errors.map(msg => {
- return `(${j.name}) ${msg}`;
- }));
- }, []),
- warnings: jsons.reduce((arr, j) => {
- return arr.concat(j.warnings.map(msg => {
- return `(${j.name}) ${msg}`;
- }));
- }, [])
- };
- if(showVersion)
- obj.version = require("../package.json").version;
- if(showHash)
- obj.hash = this.hash;
- if(options.children !== false)
- obj.children = jsons;
- return obj;
- }
-
- toString(options) {
- if(typeof options === "boolean" || typeof options === "string") {
- options = Stats.presetToOptions(options);
- } else if(!options) {
- options = {};
- }
-
- const useColors = optionOrFallback(options.colors, false);
-
- const obj = this.toJson(options, true);
-
- return Stats.jsonToString(obj, useColors);
- }
-}
-
-module.exports = MultiStats;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Stats = require("./Stats"); + +const optionOrFallback = (optionValue, fallbackValue) => + optionValue !== undefined ? optionValue : fallbackValue; + +class MultiStats { + constructor(stats) { + this.stats = stats; + this.hash = stats.map(stat => stat.hash).join(""); + } + + hasErrors() { + return this.stats + .map(stat => stat.hasErrors()) + .reduce((a, b) => a || b, false); + } + + hasWarnings() { + return this.stats + .map(stat => stat.hasWarnings()) + .reduce((a, b) => a || b, false); + } + + toJson(options, forToString) { + if (typeof options === "boolean" || typeof options === "string") { + options = Stats.presetToOptions(options); + } else if (!options) { + options = {}; + } + const jsons = this.stats.map((stat, idx) => { + const childOptions = Stats.getChildOptions(options, idx); + const obj = stat.toJson(childOptions, forToString); + obj.name = stat.compilation && stat.compilation.name; + return obj; + }); + const showVersion = + options.version === undefined + ? jsons.every(j => j.version) + : options.version !== false; + const showHash = + options.hash === undefined + ? jsons.every(j => j.hash) + : options.hash !== false; + if (showVersion) { + for (const j of jsons) { + delete j.version; + } + } + const obj = { + errors: jsons.reduce((arr, j) => { + return arr.concat( + j.errors.map(msg => { + return `(${j.name}) ${msg}`; + }) + ); + }, []), + warnings: jsons.reduce((arr, j) => { + return arr.concat( + j.warnings.map(msg => { + return `(${j.name}) ${msg}`; + }) + ); + }, []) + }; + if (showVersion) obj.version = require("../package.json").version; + if (showHash) obj.hash = this.hash; + if (options.children !== false) obj.children = jsons; + return obj; + } + + toString(options) { + if (typeof options === "boolean" || typeof options === "string") { + options = Stats.presetToOptions(options); + } else if (!options) { + options = {}; + } + + const useColors = optionOrFallback(options.colors, false); + + const obj = this.toJson(options, true); + + return Stats.jsonToString(obj, useColors); + } +} + +module.exports = MultiStats; diff --git a/node_modules/webpack/lib/MultiWatching.js b/node_modules/webpack/lib/MultiWatching.js index 95fd4075f..48e012c87 100644 --- a/node_modules/webpack/lib/MultiWatching.js +++ b/node_modules/webpack/lib/MultiWatching.js @@ -1,32 +1,38 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const asyncLib = require("async");
-
-class MultiWatching {
- constructor(watchings, compiler) {
- this.watchings = watchings;
- this.compiler = compiler;
- }
-
- invalidate() {
- this.watchings.forEach((watching) => watching.invalidate());
- }
-
- close(callback) {
- if(callback === undefined) callback = () => { /*do nothing*/ };
-
- asyncLib.forEach(this.watchings, (watching, finishedCallback) => {
- watching.close(finishedCallback);
- }, err => {
- this.compiler.applyPlugins("watch-close");
- callback(err);
- });
-
- }
-}
-
-module.exports = MultiWatching;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const asyncLib = require("neo-async"); + +class MultiWatching { + constructor(watchings, compiler) { + this.watchings = watchings; + this.compiler = compiler; + } + + invalidate() { + for (const watching of this.watchings) { + watching.invalidate(); + } + } + + close(callback) { + asyncLib.forEach( + 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; diff --git a/node_modules/webpack/lib/NamedChunksPlugin.js b/node_modules/webpack/lib/NamedChunksPlugin.js index 10f99530f..0cb5b6bf3 100644 --- a/node_modules/webpack/lib/NamedChunksPlugin.js +++ b/node_modules/webpack/lib/NamedChunksPlugin.js @@ -1,30 +1,29 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-class NamedChunksPlugin {
-
- static defaultNameResolver(chunk) {
- return chunk.name || null;
- }
-
- constructor(nameResolver) {
- this.nameResolver = nameResolver || NamedChunksPlugin.defaultNameResolver;
- }
-
- apply(compiler) {
- compiler.plugin("compilation", (compilation) => {
- compilation.plugin("before-chunk-ids", (chunks) => {
- chunks.forEach((chunk) => {
- if(chunk.id === null) {
- chunk.id = this.nameResolver(chunk);
- }
- });
- });
- });
- }
-}
-
-module.exports = NamedChunksPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +class NamedChunksPlugin { + static defaultNameResolver(chunk) { + return chunk.name || null; + } + + constructor(nameResolver) { + this.nameResolver = nameResolver || NamedChunksPlugin.defaultNameResolver; + } + + apply(compiler) { + compiler.hooks.compilation.tap("NamedChunksPlugin", compilation => { + compilation.hooks.beforeChunkIds.tap("NamedChunksPlugin", chunks => { + for (const chunk of chunks) { + if (chunk.id === null) { + chunk.id = this.nameResolver(chunk); + } + } + }); + }); + } +} + +module.exports = NamedChunksPlugin; diff --git a/node_modules/webpack/lib/NamedModulesPlugin.js b/node_modules/webpack/lib/NamedModulesPlugin.js index 37c12a9cf..a3857ac8e 100644 --- a/node_modules/webpack/lib/NamedModulesPlugin.js +++ b/node_modules/webpack/lib/NamedModulesPlugin.js @@ -1,27 +1,57 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-class NamedModulesPlugin {
- constructor(options) {
- this.options = options || {};
- }
-
- apply(compiler) {
- compiler.plugin("compilation", (compilation) => {
- compilation.plugin("before-module-ids", (modules) => {
- modules.forEach((module) => {
- if(module.id === null && module.libIdent) {
- module.id = module.libIdent({
- context: this.options.context || compiler.options.context
- });
- }
- });
- });
- });
- }
-}
-
-module.exports = NamedModulesPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const createHash = require("./util/createHash"); +const RequestShortener = require("./RequestShortener"); + +const getHash = str => { + const hash = createHash("md4"); + hash.update(str); + return hash.digest("hex").substr(0, 4); +}; + +class NamedModulesPlugin { + constructor(options) { + this.options = options || {}; + } + + apply(compiler) { + compiler.hooks.compilation.tap("NamedModulesPlugin", compilation => { + compilation.hooks.beforeModuleIds.tap("NamedModulesPlugin", modules => { + const namedModules = new Map(); + const context = this.options.context || compiler.options.context; + + for (const module of modules) { + if (module.id === null && module.libIdent) { + module.id = module.libIdent({ context }); + } + + if (module.id !== null) { + const namedModule = namedModules.get(module.id); + if (namedModule !== undefined) { + namedModule.push(module); + } else { + namedModules.set(module.id, [module]); + } + } + } + + for (const namedModule of namedModules.values()) { + if (namedModule.length > 1) { + for (const module of namedModule) { + const requestShortener = new RequestShortener(context); + module.id = `${module.id}?${getHash( + requestShortener.shorten(module.identifier()) + )}`; + } + } + } + }); + }); + } +} + +module.exports = NamedModulesPlugin; diff --git a/node_modules/webpack/lib/NewWatchingPlugin.js b/node_modules/webpack/lib/NewWatchingPlugin.js deleted file mode 100644 index 29e2fa326..000000000 --- a/node_modules/webpack/lib/NewWatchingPlugin.js +++ /dev/null @@ -1,15 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-class NewWatchingPlugin {
- apply(compiler) {
- compiler.plugin("compilation", function(compilation) {
- compilation.warnings.push(new Error("The 'NewWatchingPlugin' is no longer necessary (now default)"));
- });
- }
-}
-
-module.exports = NewWatchingPlugin;
diff --git a/node_modules/webpack/lib/NoEmitOnErrorsPlugin.js b/node_modules/webpack/lib/NoEmitOnErrorsPlugin.js index c650253e5..2c37c4979 100644 --- a/node_modules/webpack/lib/NoEmitOnErrorsPlugin.js +++ b/node_modules/webpack/lib/NoEmitOnErrorsPlugin.js @@ -1,22 +1,20 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-class NoEmitOnErrorsPlugin {
- apply(compiler) {
- compiler.plugin("should-emit", (compilation) => {
- if(compilation.errors.length > 0)
- return false;
- });
- compiler.plugin("compilation", (compilation) => {
- compilation.plugin("should-record", () => {
- if(compilation.errors.length > 0)
- return false;
- });
- });
- }
-}
-
-module.exports = NoEmitOnErrorsPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +class NoEmitOnErrorsPlugin { + 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; diff --git a/node_modules/webpack/lib/NoErrorsPlugin.js b/node_modules/webpack/lib/NoErrorsPlugin.js deleted file mode 100644 index 0922f72f9..000000000 --- a/node_modules/webpack/lib/NoErrorsPlugin.js +++ /dev/null @@ -1,29 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-let deprecationReported = false;
-
-class NoErrorsPlugin {
- apply(compiler) {
- compiler.plugin("should-emit", (compilation) => {
- if(!deprecationReported) {
- compilation.warnings.push("webpack: Using NoErrorsPlugin is deprecated.\n" +
- "Use NoEmitOnErrorsPlugin instead.\n");
- deprecationReported = true;
- }
- if(compilation.errors.length > 0)
- return false;
- });
- compiler.plugin("compilation", (compilation) => {
- compilation.plugin("should-record", () => {
- if(compilation.errors.length > 0)
- return false;
- });
- });
- }
-}
-
-module.exports = NoErrorsPlugin;
diff --git a/node_modules/webpack/lib/NodeStuffPlugin.js b/node_modules/webpack/lib/NodeStuffPlugin.js index b18ed173c..75d2e73b0 100644 --- a/node_modules/webpack/lib/NodeStuffPlugin.js +++ b/node_modules/webpack/lib/NodeStuffPlugin.js @@ -1,97 +1,197 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const path = require("path");
-const ParserHelpers = require("./ParserHelpers");
-const ConstDependency = require("./dependencies/ConstDependency");
-
-const NullFactory = require("./NullFactory");
-
-class NodeStuffPlugin {
- constructor(options) {
- this.options = options;
- }
-
- apply(compiler) {
- const options = this.options;
- compiler.plugin("compilation", (compilation, params) => {
- compilation.dependencyFactories.set(ConstDependency, new NullFactory());
- compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
-
- params.normalModuleFactory.plugin("parser", (parser, parserOptions) => {
-
- if(parserOptions.node === false)
- return;
-
- let localOptions = options;
- if(parserOptions.node)
- localOptions = Object.assign({}, localOptions, parserOptions.node);
-
- function setConstant(expressionName, value) {
- parser.plugin(`expression ${expressionName}`, function() {
- this.state.current.addVariable(expressionName, JSON.stringify(value));
- return true;
- });
- }
-
- function setModuleConstant(expressionName, fn) {
- parser.plugin(`expression ${expressionName}`, function() {
- this.state.current.addVariable(expressionName, JSON.stringify(fn(this.state.module)));
- return true;
- });
- }
- const context = compiler.context;
- if(localOptions.__filename === "mock") {
- setConstant("__filename", "/index.js");
- } else if(localOptions.__filename) {
- setModuleConstant("__filename", module => path.relative(context, module.resource));
- }
- parser.plugin("evaluate Identifier __filename", function(expr) {
- if(!this.state.module) return;
- const resource = this.state.module.resource;
- const i = resource.indexOf("?");
- return ParserHelpers.evaluateToString(i < 0 ? resource : resource.substr(0, i))(expr);
- });
- if(localOptions.__dirname === "mock") {
- setConstant("__dirname", "/");
- } else if(localOptions.__dirname) {
- setModuleConstant("__dirname", module => path.relative(context, module.context));
- }
- parser.plugin("evaluate Identifier __dirname", function(expr) {
- if(!this.state.module) return;
- return ParserHelpers.evaluateToString(this.state.module.context)(expr);
- });
- parser.plugin("expression require.main", ParserHelpers.toConstantDependency("__webpack_require__.c[__webpack_require__.s]"));
- parser.plugin(
- "expression require.extensions",
- ParserHelpers.expressionIsUnsupported("require.extensions is not supported by webpack. Use a loader instead.")
- );
- parser.plugin("expression module.loaded", ParserHelpers.toConstantDependency("module.l"));
- parser.plugin("expression module.id", ParserHelpers.toConstantDependency("module.i"));
- parser.plugin("expression module.exports", function() {
- const module = this.state.module;
- const isHarmony = module.meta && module.meta.harmonyModule;
- if(!isHarmony)
- return true;
- });
- parser.plugin("evaluate Identifier module.hot", ParserHelpers.evaluateToIdentifier("module.hot", false));
- parser.plugin("expression module", function() {
- const module = this.state.module;
- const isHarmony = module.meta && module.meta.harmonyModule;
- let moduleJsPath = path.join(__dirname, "..", "buildin", isHarmony ? "harmony-module.js" : "module.js");
- if(module.context) {
- moduleJsPath = path.relative(this.state.module.context, moduleJsPath);
- if(!/^[A-Z]:/i.test(moduleJsPath)) {
- moduleJsPath = `./${moduleJsPath.replace(/\\/g, "/")}`;
- }
- }
- return ParserHelpers.addParsedVariableToModule(this, "module", `require(${JSON.stringify(moduleJsPath)})(module)`);
- });
- });
- });
- }
-}
-module.exports = NodeStuffPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const path = require("path"); +const ParserHelpers = require("./ParserHelpers"); +const ConstDependency = require("./dependencies/ConstDependency"); + +const NullFactory = require("./NullFactory"); + +class NodeStuffPlugin { + constructor(options) { + this.options = options; + } + + apply(compiler) { + const options = this.options; + compiler.hooks.compilation.tap( + "NodeStuffPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set(ConstDependency, new NullFactory()); + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); + + const handler = (parser, parserOptions) => { + if (parserOptions.node === false) return; + + let localOptions = options; + if (parserOptions.node) { + localOptions = Object.assign({}, localOptions, parserOptions.node); + } + + const setConstant = (expressionName, value) => { + parser.hooks.expression + .for(expressionName) + .tap("NodeStuffPlugin", () => { + parser.state.current.addVariable( + expressionName, + JSON.stringify(value) + ); + return true; + }); + }; + + const setModuleConstant = (expressionName, fn) => { + parser.hooks.expression + .for(expressionName) + .tap("NodeStuffPlugin", () => { + parser.state.current.addVariable( + expressionName, + JSON.stringify(fn(parser.state.module)) + ); + return true; + }); + }; + const context = compiler.context; + if (localOptions.__filename === "mock") { + setConstant("__filename", "/index.js"); + } else if (localOptions.__filename) { + setModuleConstant("__filename", module => + path.relative(context, module.resource) + ); + } + parser.hooks.evaluateIdentifier + .for("__filename") + .tap("NodeStuffPlugin", expr => { + if (!parser.state.module) return; + const resource = parser.state.module.resource; + const i = resource.indexOf("?"); + return ParserHelpers.evaluateToString( + i < 0 ? resource : resource.substr(0, i) + )(expr); + }); + if (localOptions.__dirname === "mock") { + setConstant("__dirname", "/"); + } else if (localOptions.__dirname) { + setModuleConstant("__dirname", module => + path.relative(context, module.context) + ); + } + parser.hooks.evaluateIdentifier + .for("__dirname") + .tap("NodeStuffPlugin", expr => { + if (!parser.state.module) return; + return ParserHelpers.evaluateToString( + parser.state.module.context + )(expr); + }); + parser.hooks.expression + .for("require.main") + .tap( + "NodeStuffPlugin", + ParserHelpers.toConstantDependencyWithWebpackRequire( + parser, + "__webpack_require__.c[__webpack_require__.s]" + ) + ); + parser.hooks.expression + .for("require.extensions") + .tap( + "NodeStuffPlugin", + ParserHelpers.expressionIsUnsupported( + parser, + "require.extensions is not supported by webpack. Use a loader instead." + ) + ); + parser.hooks.expression + .for("require.main.require") + .tap( + "NodeStuffPlugin", + ParserHelpers.expressionIsUnsupported( + parser, + "require.main.require is not supported by webpack." + ) + ); + parser.hooks.expression + .for("module.parent.require") + .tap( + "NodeStuffPlugin", + ParserHelpers.expressionIsUnsupported( + parser, + "module.parent.require is not supported by webpack." + ) + ); + parser.hooks.expression + .for("module.loaded") + .tap("NodeStuffPlugin", expr => { + parser.state.module.buildMeta.moduleConcatenationBailout = + "module.loaded"; + return ParserHelpers.toConstantDependency(parser, "module.l")( + expr + ); + }); + parser.hooks.expression + .for("module.id") + .tap("NodeStuffPlugin", expr => { + parser.state.module.buildMeta.moduleConcatenationBailout = + "module.id"; + return ParserHelpers.toConstantDependency(parser, "module.i")( + expr + ); + }); + parser.hooks.expression + .for("module.exports") + .tap("NodeStuffPlugin", () => { + const module = parser.state.module; + const isHarmony = + module.buildMeta && module.buildMeta.exportsType; + if (!isHarmony) return true; + }); + parser.hooks.evaluateIdentifier + .for("module.hot") + .tap( + "NodeStuffPlugin", + ParserHelpers.evaluateToIdentifier("module.hot", false) + ); + parser.hooks.expression.for("module").tap("NodeStuffPlugin", () => { + const module = parser.state.module; + const isHarmony = module.buildMeta && module.buildMeta.exportsType; + let moduleJsPath = path.join( + __dirname, + "..", + "buildin", + isHarmony ? "harmony-module.js" : "module.js" + ); + if (module.context) { + moduleJsPath = path.relative( + parser.state.module.context, + moduleJsPath + ); + if (!/^[A-Z]:/i.test(moduleJsPath)) { + moduleJsPath = `./${moduleJsPath.replace(/\\/g, "/")}`; + } + } + return ParserHelpers.addParsedVariableToModule( + parser, + "module", + `require(${JSON.stringify(moduleJsPath)})(module)` + ); + }); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("NodeStuffPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("NodeStuffPlugin", handler); + } + ); + } +} +module.exports = NodeStuffPlugin; diff --git a/node_modules/webpack/lib/NormalModule.js b/node_modules/webpack/lib/NormalModule.js index c3288bf0d..fdabc3000 100644 --- a/node_modules/webpack/lib/NormalModule.js +++ b/node_modules/webpack/lib/NormalModule.js @@ -1,556 +1,542 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const path = require("path");
-const NativeModule = require("module");
-const crypto = require("crypto");
-
-const SourceMapSource = require("webpack-sources").SourceMapSource;
-const OriginalSource = require("webpack-sources").OriginalSource;
-const RawSource = require("webpack-sources").RawSource;
-const ReplaceSource = require("webpack-sources").ReplaceSource;
-const CachedSource = require("webpack-sources").CachedSource;
-const LineToLineMappedSource = require("webpack-sources").LineToLineMappedSource;
-
-const WebpackError = require("./WebpackError");
-const Module = require("./Module");
-const ModuleParseError = require("./ModuleParseError");
-const ModuleBuildError = require("./ModuleBuildError");
-const ModuleError = require("./ModuleError");
-const ModuleWarning = require("./ModuleWarning");
-
-const runLoaders = require("loader-runner").runLoaders;
-const getContext = require("loader-runner").getContext;
-
-function asString(buf) {
- if(Buffer.isBuffer(buf)) {
- return buf.toString("utf-8");
- }
- return buf;
-}
-
-function contextify(context, request) {
- return request.split("!").map(function(r) {
- const splitPath = r.split("?");
- splitPath[0] = path.relative(context, splitPath[0]);
- if(path.sep === "\\")
- splitPath[0] = splitPath[0].replace(/\\/g, "/");
- if(splitPath[0].indexOf("../") !== 0)
- splitPath[0] = "./" + splitPath[0];
- return splitPath.join("?");
- }).join("!");
-}
-
-class NonErrorEmittedError extends WebpackError {
- constructor(error) {
- super();
-
- this.name = "NonErrorEmittedError";
- this.message = "(Emitted value instead of an instance of Error) " + error;
-
- Error.captureStackTrace(this, this.constructor);
- }
-}
-
-const dependencyTemplatesHashMap = new WeakMap();
-
-class NormalModule extends Module {
-
- constructor(request, userRequest, rawRequest, loaders, resource, parser) {
- super();
- this.request = request;
- this.userRequest = userRequest;
- this.rawRequest = rawRequest;
- this.parser = parser;
- this.resource = resource;
- this.context = getContext(resource);
- this.loaders = loaders;
- this.fileDependencies = [];
- this.contextDependencies = [];
- this.warnings = [];
- this.errors = [];
- this.error = null;
- this._source = null;
- this.assets = {};
- this.built = false;
- this._cachedSource = null;
- }
-
- identifier() {
- return this.request;
- }
-
- readableIdentifier(requestShortener) {
- return requestShortener.shorten(this.userRequest);
- }
-
- libIdent(options) {
- return contextify(options.context, this.userRequest);
- }
-
- nameForCondition() {
- const idx = this.resource.indexOf("?");
- if(idx >= 0) return this.resource.substr(0, idx);
- return this.resource;
- }
-
- createSourceForAsset(name, content, sourceMap) {
- if(!sourceMap) {
- return new RawSource(content);
- }
-
- if(typeof sourceMap === "string") {
- return new OriginalSource(content, sourceMap);
- }
-
- return new SourceMapSource(content, name, sourceMap);
- }
-
- createLoaderContext(resolver, options, compilation, fs) {
- const loaderContext = {
- version: 2,
- emitWarning: (warning) => {
- if(!(warning instanceof Error))
- warning = new NonErrorEmittedError(warning);
- this.warnings.push(new ModuleWarning(this, warning));
- },
- emitError: (error) => {
- if(!(error instanceof Error))
- error = new NonErrorEmittedError(error);
- this.errors.push(new ModuleError(this, error));
- },
- exec: (code, filename) => {
- const module = new NativeModule(filename, this);
- module.paths = NativeModule._nodeModulePaths(this.context);
- module.filename = filename;
- module._compile(code, filename);
- return module.exports;
- },
- resolve(context, request, callback) {
- resolver.resolve({}, context, request, callback);
- },
- resolveSync(context, request) {
- return resolver.resolveSync({}, context, request);
- },
- emitFile: (name, content, sourceMap) => {
- this.assets[name] = this.createSourceForAsset(name, content, sourceMap);
- },
- options: options,
- webpack: true,
- sourceMap: !!this.useSourceMap,
- _module: this,
- _compilation: compilation,
- _compiler: compilation.compiler,
- fs: fs,
- };
-
- compilation.applyPlugins("normal-module-loader", loaderContext, this);
- if(options.loader)
- Object.assign(loaderContext, options.loader);
-
- return loaderContext;
- }
-
- createSource(source, resourceBuffer, sourceMap) {
- // if there is no identifier return raw source
- if(!this.identifier) {
- return new RawSource(source);
- }
-
- // from here on we assume we have an identifier
- const identifier = this.identifier();
-
- if(this.lineToLine && resourceBuffer) {
- return new LineToLineMappedSource(
- source, identifier, asString(resourceBuffer));
- }
-
- if(this.useSourceMap && sourceMap) {
- return new SourceMapSource(source, identifier, sourceMap);
- }
-
- return new OriginalSource(source, identifier);
- }
-
- doBuild(options, compilation, resolver, fs, callback) {
- this.cacheable = false;
- const loaderContext = this.createLoaderContext(resolver, options, compilation, fs);
-
- runLoaders({
- resource: this.resource,
- loaders: this.loaders,
- context: loaderContext,
- readResource: fs.readFile.bind(fs)
- }, (err, result) => {
- if(result) {
- this.cacheable = result.cacheable;
- this.fileDependencies = result.fileDependencies;
- this.contextDependencies = result.contextDependencies;
- }
-
- if(err) {
- const error = new ModuleBuildError(this, err);
- return callback(error);
- }
-
- const resourceBuffer = result.resourceBuffer;
- const source = result.result[0];
- const sourceMap = result.result[1];
-
- if(!Buffer.isBuffer(source) && typeof source !== "string") {
- const error = new ModuleBuildError(this, new Error("Final loader didn't return a Buffer or String"));
- return callback(error);
- }
-
- this._source = this.createSource(asString(source), resourceBuffer, sourceMap);
- return callback();
- });
- }
-
- disconnect() {
- this.built = false;
- super.disconnect();
- }
-
- markModuleAsErrored(error) {
- this.meta = null;
- this.error = error;
- this.errors.push(this.error);
- this._source = new RawSource("throw new Error(" + JSON.stringify(this.error.message) + ");");
- }
-
- applyNoParseRule(rule, content) {
- // must start with "rule" if rule is a string
- if(typeof rule === "string") {
- return content.indexOf(rule) === 0;
- }
-
- if(typeof rule === "function") {
- return rule(content);
- }
- // we assume rule is a regexp
- return rule.test(content);
- }
-
- // check if module should not be parsed
- // returns "true" if the module should !not! be parsed
- // returns "false" if the module !must! be parsed
- shouldPreventParsing(noParseRule, request) {
- // if no noParseRule exists, return false
- // the module !must! be parsed.
- if(!noParseRule) {
- return false;
- }
-
- // we only have one rule to check
- if(!Array.isArray(noParseRule)) {
- // returns "true" if the module is !not! to be parsed
- return this.applyNoParseRule(noParseRule, request);
- }
-
- for(let i = 0; i < noParseRule.length; i++) {
- const rule = noParseRule[i];
- // early exit on first truthy match
- // this module is !not! to be parsed
- if(this.applyNoParseRule(rule, request)) {
- return true;
- }
- }
- // no match found, so this module !should! be parsed
- return false;
- }
-
- build(options, compilation, resolver, fs, callback) {
- this.buildTimestamp = Date.now();
- this.built = true;
- this._source = null;
- this.error = null;
- this.errors.length = 0;
- this.warnings.length = 0;
- this.meta = {};
-
- return this.doBuild(options, compilation, resolver, fs, (err) => {
- this.dependencies.length = 0;
- this.variables.length = 0;
- this.blocks.length = 0;
- this._cachedSource = null;
-
- // if we have an error mark module as failed and exit
- if(err) {
- this.markModuleAsErrored(err);
- return callback();
- }
-
- // check if this module should !not! be parsed.
- // if so, exit here;
- const noParseRule = options.module && options.module.noParse;
- if(this.shouldPreventParsing(noParseRule, this.request)) {
- return callback();
- }
-
- try {
- this.parser.parse(this._source.source(), {
- current: this,
- module: this,
- compilation: compilation,
- options: options
- });
- } catch(e) {
- const source = this._source.source();
- const error = new ModuleParseError(this, source, e);
- this.markModuleAsErrored(error);
- return callback();
- }
- return callback();
- });
- }
-
- getHashDigest(dependencyTemplates) {
- let dtHash = dependencyTemplatesHashMap.get("hash");
- const hash = crypto.createHash("md5");
- this.updateHash(hash);
- hash.update(`${dtHash}`);
- return hash.digest("hex");
- }
-
- sourceDependency(dependency, dependencyTemplates, source, outputOptions, requestShortener) {
- const template = dependencyTemplates.get(dependency.constructor);
- if(!template) throw new Error("No template for dependency: " + dependency.constructor.name);
- template.apply(dependency, source, outputOptions, requestShortener, dependencyTemplates);
- }
-
- sourceVariables(variable, availableVars, dependencyTemplates, outputOptions, requestShortener) {
- const name = variable.name;
- const expr = variable.expressionSource(dependencyTemplates, outputOptions, requestShortener);
-
- if(availableVars.some(v => v.name === name && v.expression.source() === expr.source())) {
- return;
- }
- return {
- name: name,
- expression: expr
- };
- }
-
- /*
- * creates the start part of a IIFE around the module to inject a variable name
- * (function(...){ <- this part
- * }.call(...))
- */
- variableInjectionFunctionWrapperStartCode(varNames) {
- const args = varNames.join(", ");
- return `/* WEBPACK VAR INJECTION */(function(${args}) {`;
- }
-
- contextArgument(block) {
- if(this === block) {
- return this.exportsArgument || "exports";
- }
- return "this";
- }
-
- /*
- * creates the end part of a IIFE around the module to inject a variable name
- * (function(...){
- * }.call(...)) <- this part
- */
- variableInjectionFunctionWrapperEndCode(varExpressions, block) {
- const firstParam = this.contextArgument(block);
- const furtherParams = varExpressions.map(e => e.source()).join(", ");
- return `}.call(${firstParam}, ${furtherParams}))`;
- }
-
- splitVariablesInUniqueNamedChunks(vars) {
- const startState = [
- []
- ];
- return vars.reduce((chunks, variable) => {
- const current = chunks[chunks.length - 1];
- // check if variable with same name exists already
- // if so create a new chunk of variables.
- const variableNameAlreadyExists = current.some(v => v.name === variable.name);
-
- if(variableNameAlreadyExists) {
- // start new chunk with current variable
- chunks.push([variable]);
- } else {
- // else add it to current chunk
- current.push(variable);
- }
- return chunks;
- }, startState);
- }
-
- sourceBlock(block, availableVars, dependencyTemplates, source, outputOptions, requestShortener) {
- block.dependencies.forEach((dependency) => this.sourceDependency(
- dependency, dependencyTemplates, source, outputOptions, requestShortener));
-
- /**
- * Get the variables of all blocks that we need to inject.
- * These will contain the variable name and its expression.
- * The name will be added as a paramter in a IIFE the expression as its value.
- */
- const vars = block.variables.reduce((result, value) => {
- const variable = this.sourceVariables(
- value, availableVars, dependencyTemplates, outputOptions, requestShortener);
-
- if(variable) {
- result.push(variable);
- }
-
- return result;
- }, []);
-
- /**
- * if we actually have variables
- * this is important as how #splitVariablesInUniqueNamedChunks works
- * it will always return an array in an array which would lead to a IIFE wrapper around
- * a module if we do this with an empty vars array.
- */
- if(vars.length > 0) {
- /**
- * Split all variables up into chunks of unique names.
- * e.g. imagine you have the following variable names that need to be injected:
- * [foo, bar, baz, foo, some, more]
- * we can not inject "foo" twice, therefore we just make two IIFEs like so:
- * (function(foo, bar, baz){
- * (function(foo, some, more){
- * ...
- * }(...));
- * }(...));
- *
- * "splitVariablesInUniqueNamedChunks" splits the variables shown above up to this:
- * [[foo, bar, baz], [foo, some, more]]
- */
- const injectionVariableChunks = this.splitVariablesInUniqueNamedChunks(vars);
-
- // create all the beginnings of IIFEs
- const functionWrapperStarts = injectionVariableChunks.map((variableChunk) => {
- return this.variableInjectionFunctionWrapperStartCode(
- variableChunk.map(variable => variable.name)
- );
- });
-
- // and all the ends
- const functionWrapperEnds = injectionVariableChunks.map((variableChunk) => {
- return this.variableInjectionFunctionWrapperEndCode(
- variableChunk.map(variable => variable.expression), block
- );
- });
-
- // join them to one big string
- const varStartCode = functionWrapperStarts.join("");
-
- // reverse the ends first before joining them, as the last added must be the inner most
- const varEndCode = functionWrapperEnds.reverse().join("");
-
- // if we have anything, add it to the source
- if(varStartCode && varEndCode) {
- const start = block.range ? block.range[0] : -10;
- const end = block.range ? block.range[1] : (this._source.size() + 1);
- source.insert(start + 0.5, varStartCode);
- source.insert(end + 0.5, "\n/* WEBPACK VAR INJECTION */" + varEndCode);
- }
- }
-
- block.blocks.forEach((block) =>
- this.sourceBlock(
- block,
- availableVars.concat(vars),
- dependencyTemplates,
- source,
- outputOptions,
- requestShortener
- )
- );
- }
-
- source(dependencyTemplates, outputOptions, requestShortener) {
- const hashDigest = this.getHashDigest(dependencyTemplates);
- if(this._cachedSource && this._cachedSource.hash === hashDigest) {
- return this._cachedSource.source;
- }
-
- if(!this._source) {
- return new RawSource("throw new Error('No source available');");
- }
-
- const source = new ReplaceSource(this._source);
- this._cachedSource = {
- source: source,
- hash: hashDigest
- };
-
- this.sourceBlock(this, [], dependencyTemplates, source, outputOptions, requestShortener);
- return new CachedSource(source);
- }
-
- originalSource() {
- return this._source;
- }
-
- getHighestTimestamp(keys, timestampsByKey) {
- let highestTimestamp = 0;
- for(let i = 0; i < keys.length; i++) {
- const key = keys[i];
- const timestamp = timestampsByKey[key];
- // if there is no timestamp yet, early return with Infinity
- if(!timestamp) return Infinity;
- highestTimestamp = Math.max(highestTimestamp, timestamp);
- }
- return highestTimestamp;
- }
-
- needRebuild(fileTimestamps, contextTimestamps) {
- const highestFileDepTimestamp = this.getHighestTimestamp(
- this.fileDependencies, fileTimestamps);
- // if the hightest is Infinity, we need a rebuild
- // exit early here.
- if(highestFileDepTimestamp === Infinity) {
- return true;
- }
-
- const highestContextDepTimestamp = this.getHighestTimestamp(
- this.contextDependencies, contextTimestamps);
-
- // Again if the hightest is Infinity, we need a rebuild
- // exit early here.
- if(highestContextDepTimestamp === Infinity) {
- return true;
- }
-
- // else take the highest of file and context timestamps and compare
- // to last build timestamp
- return Math.max(highestContextDepTimestamp, highestFileDepTimestamp) >= this.buildTimestamp;
- }
-
- size() {
- return this._source ? this._source.size() : -1;
- }
-
- updateHashWithSource(hash) {
- if(!this._source) {
- hash.update("null");
- return;
- }
- hash.update("source");
- this._source.updateHash(hash);
- }
-
- updateHashWithMeta(hash) {
- hash.update("meta");
- hash.update(JSON.stringify(this.meta));
- }
-
- updateHash(hash) {
- this.updateHashWithSource(hash);
- this.updateHashWithMeta(hash);
- super.updateHash(hash);
- }
-
-}
-
-module.exports = NormalModule;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const NativeModule = require("module"); + +const { + CachedSource, + LineToLineMappedSource, + OriginalSource, + RawSource, + SourceMapSource +} = require("webpack-sources"); +const { getContext, runLoaders } = require("loader-runner"); + +const WebpackError = require("./WebpackError"); +const Module = require("./Module"); +const ModuleParseError = require("./ModuleParseError"); +const ModuleBuildError = require("./ModuleBuildError"); +const ModuleError = require("./ModuleError"); +const ModuleWarning = require("./ModuleWarning"); +const createHash = require("./util/createHash"); +const contextify = require("./util/identifier").contextify; + +/** @typedef {import("./util/createHash").Hash} Hash */ + +const asString = buf => { + if (Buffer.isBuffer(buf)) { + return buf.toString("utf-8"); + } + return buf; +}; + +const asBuffer = str => { + if (!Buffer.isBuffer(str)) { + return Buffer.from(str, "utf-8"); + } + return str; +}; + +class NonErrorEmittedError extends WebpackError { + constructor(error) { + super(); + + this.name = "NonErrorEmittedError"; + this.message = "(Emitted value instead of an instance of Error) " + error; + + Error.captureStackTrace(this, this.constructor); + } +} + +/** + * @typedef {Object} CachedSourceEntry + * @property {TODO} source the generated source + * @property {string} hash the hash value + */ + +class NormalModule extends Module { + constructor({ + type, + request, + userRequest, + rawRequest, + loaders, + resource, + matchResource, + parser, + generator, + resolveOptions + }) { + super(type, getContext(resource)); + + // Info from Factory + this.request = request; + this.userRequest = userRequest; + this.rawRequest = rawRequest; + this.binary = type.startsWith("webassembly"); + this.parser = parser; + this.generator = generator; + this.resource = resource; + this.matchResource = matchResource; + this.loaders = loaders; + if (resolveOptions !== undefined) this.resolveOptions = resolveOptions; + + // Info from Build + this.error = null; + this._source = null; + this._buildHash = ""; + this.buildTimestamp = undefined; + /** @private @type {Map<string, CachedSourceEntry>} */ + this._cachedSources = new Map(); + + // Options for the NormalModule set by plugins + // TODO refactor this -> options object filled from Factory + this.useSourceMap = false; + this.lineToLine = false; + + // Cache + this._lastSuccessfulBuildMeta = {}; + } + + identifier() { + return this.request; + } + + readableIdentifier(requestShortener) { + return requestShortener.shorten(this.userRequest); + } + + libIdent(options) { + return contextify(options.context, this.userRequest); + } + + nameForCondition() { + const resource = this.matchResource || this.resource; + const idx = resource.indexOf("?"); + if (idx >= 0) return resource.substr(0, idx); + return resource; + } + + updateCacheModule(module) { + this.type = module.type; + this.request = module.request; + this.userRequest = module.userRequest; + this.rawRequest = module.rawRequest; + this.parser = module.parser; + this.generator = module.generator; + this.resource = module.resource; + this.matchResource = module.matchResource; + this.loaders = module.loaders; + this.resolveOptions = module.resolveOptions; + } + + createSourceForAsset(name, content, sourceMap) { + if (!sourceMap) { + return new RawSource(content); + } + + if (typeof sourceMap === "string") { + return new OriginalSource(content, sourceMap); + } + + return new SourceMapSource(content, name, sourceMap); + } + + createLoaderContext(resolver, options, compilation, fs) { + const requestShortener = compilation.runtimeTemplate.requestShortener; + const loaderContext = { + version: 2, + emitWarning: warning => { + if (!(warning instanceof Error)) { + warning = new NonErrorEmittedError(warning); + } + const currentLoader = this.getCurrentLoader(loaderContext); + this.warnings.push( + new ModuleWarning(this, warning, { + from: requestShortener.shorten(currentLoader.loader) + }) + ); + }, + emitError: error => { + if (!(error instanceof Error)) { + error = new NonErrorEmittedError(error); + } + const currentLoader = this.getCurrentLoader(loaderContext); + this.errors.push( + new ModuleError(this, error, { + from: requestShortener.shorten(currentLoader.loader) + }) + ); + }, + // TODO remove in webpack 5 + exec: (code, filename) => { + // @ts-ignore Argument of type 'this' is not assignable to parameter of type 'Module'. + const module = new NativeModule(filename, this); + // @ts-ignore _nodeModulePaths is deprecated and undocumented Node.js API + module.paths = NativeModule._nodeModulePaths(this.context); + module.filename = filename; + module._compile(code, filename); + return module.exports; + }, + resolve(context, request, callback) { + resolver.resolve({}, context, request, {}, callback); + }, + emitFile: (name, content, sourceMap) => { + if (!this.buildInfo.assets) { + this.buildInfo.assets = Object.create(null); + } + this.buildInfo.assets[name] = this.createSourceForAsset( + name, + content, + sourceMap + ); + }, + rootContext: options.context, + webpack: true, + sourceMap: !!this.useSourceMap, + _module: this, + _compilation: compilation, + _compiler: compilation.compiler, + fs: fs + }; + + compilation.hooks.normalModuleLoader.call(loaderContext, this); + if (options.loader) { + Object.assign(loaderContext, options.loader); + } + + return loaderContext; + } + + getCurrentLoader(loaderContext, index = loaderContext.loaderIndex) { + if ( + this.loaders && + this.loaders.length && + index < this.loaders.length && + index >= 0 && + this.loaders[index] + ) { + return this.loaders[index]; + } + return null; + } + + createSource(source, resourceBuffer, sourceMap) { + // if there is no identifier return raw source + if (!this.identifier) { + return new RawSource(source); + } + + // from here on we assume we have an identifier + const identifier = this.identifier(); + + if (this.lineToLine && resourceBuffer) { + return new LineToLineMappedSource( + source, + identifier, + asString(resourceBuffer) + ); + } + + if (this.useSourceMap && sourceMap) { + return new SourceMapSource(source, identifier, sourceMap); + } + + if (Buffer.isBuffer(source)) { + // @ts-ignore + // TODO We need to fix @types/webpack-sources to allow RawSource to take a Buffer | string + return new RawSource(source); + } + + return new OriginalSource(source, identifier); + } + + doBuild(options, compilation, resolver, fs, callback) { + const loaderContext = this.createLoaderContext( + resolver, + options, + compilation, + fs + ); + + runLoaders( + { + resource: this.resource, + loaders: this.loaders, + context: loaderContext, + readResource: fs.readFile.bind(fs) + }, + (err, result) => { + if (result) { + this.buildInfo.cacheable = result.cacheable; + this.buildInfo.fileDependencies = new Set(result.fileDependencies); + this.buildInfo.contextDependencies = new Set( + result.contextDependencies + ); + } + + if (err) { + if (!(err instanceof Error)) { + err = new NonErrorEmittedError(err); + } + const currentLoader = this.getCurrentLoader(loaderContext); + const error = new ModuleBuildError(this, err, { + from: + currentLoader && + compilation.runtimeTemplate.requestShortener.shorten( + currentLoader.loader + ) + }); + return callback(error); + } + + const resourceBuffer = result.resourceBuffer; + const source = result.result[0]; + const sourceMap = result.result.length >= 1 ? result.result[1] : null; + const extraInfo = result.result.length >= 2 ? result.result[2] : null; + + if (!Buffer.isBuffer(source) && typeof source !== "string") { + const currentLoader = this.getCurrentLoader(loaderContext, 0); + const err = new Error( + `Final loader (${ + currentLoader + ? compilation.runtimeTemplate.requestShortener.shorten( + currentLoader.loader + ) + : "unknown" + }) didn't return a Buffer or String` + ); + const error = new ModuleBuildError(this, err); + return callback(error); + } + + this._source = this.createSource( + this.binary ? asBuffer(source) : asString(source), + resourceBuffer, + sourceMap + ); + this._ast = + typeof extraInfo === "object" && + extraInfo !== null && + extraInfo.webpackAST !== undefined + ? extraInfo.webpackAST + : null; + return callback(); + } + ); + } + + markModuleAsErrored(error) { + // Restore build meta from successful build to keep importing state + this.buildMeta = Object.assign({}, this._lastSuccessfulBuildMeta); + + this.error = error; + this.errors.push(this.error); + this._source = new RawSource( + "throw new Error(" + JSON.stringify(this.error.message) + ");" + ); + this._ast = null; + } + + applyNoParseRule(rule, content) { + // must start with "rule" if rule is a string + if (typeof rule === "string") { + return content.indexOf(rule) === 0; + } + + if (typeof rule === "function") { + return rule(content); + } + // we assume rule is a regexp + return rule.test(content); + } + + // check if module should not be parsed + // returns "true" if the module should !not! be parsed + // returns "false" if the module !must! be parsed + shouldPreventParsing(noParseRule, request) { + // if no noParseRule exists, return false + // the module !must! be parsed. + if (!noParseRule) { + return false; + } + + // we only have one rule to check + if (!Array.isArray(noParseRule)) { + // returns "true" if the module is !not! to be parsed + return this.applyNoParseRule(noParseRule, request); + } + + for (let i = 0; i < noParseRule.length; i++) { + const rule = noParseRule[i]; + // early exit on first truthy match + // this module is !not! to be parsed + if (this.applyNoParseRule(rule, request)) { + return true; + } + } + // no match found, so this module !should! be parsed + return false; + } + + _initBuildHash(compilation) { + const hash = createHash(compilation.outputOptions.hashFunction); + if (this._source) { + hash.update("source"); + this._source.updateHash(hash); + } + hash.update("meta"); + hash.update(JSON.stringify(this.buildMeta)); + this._buildHash = hash.digest("hex"); + } + + build(options, compilation, resolver, fs, callback) { + this.buildTimestamp = Date.now(); + this.built = true; + this._source = null; + this._ast = null; + this._buildHash = ""; + this.error = null; + this.errors.length = 0; + this.warnings.length = 0; + this.buildMeta = {}; + this.buildInfo = { + cacheable: false, + fileDependencies: new Set(), + contextDependencies: new Set() + }; + + return this.doBuild(options, compilation, resolver, fs, err => { + this._cachedSources.clear(); + + // if we have an error mark module as failed and exit + if (err) { + this.markModuleAsErrored(err); + this._initBuildHash(compilation); + return callback(); + } + + // check if this module should !not! be parsed. + // if so, exit here; + const noParseRule = options.module && options.module.noParse; + if (this.shouldPreventParsing(noParseRule, this.request)) { + this._initBuildHash(compilation); + return callback(); + } + + const handleParseError = e => { + const source = this._source.source(); + const error = new ModuleParseError(this, source, e); + this.markModuleAsErrored(error); + this._initBuildHash(compilation); + return callback(); + }; + + const handleParseResult = result => { + this._lastSuccessfulBuildMeta = this.buildMeta; + this._initBuildHash(compilation); + return callback(); + }; + + try { + const result = this.parser.parse( + this._ast || this._source.source(), + { + current: this, + module: this, + compilation: compilation, + options: options + }, + (err, result) => { + if (err) { + handleParseError(err); + } else { + handleParseResult(result); + } + } + ); + if (result !== undefined) { + // parse is sync + handleParseResult(result); + } + } catch (e) { + handleParseError(e); + } + }); + } + + getHashDigest(dependencyTemplates) { + // TODO webpack 5 refactor + let dtHash = dependencyTemplates.get("hash"); + return `${this.hash}-${dtHash}`; + } + + source(dependencyTemplates, runtimeTemplate, type = "javascript") { + const hashDigest = this.getHashDigest(dependencyTemplates); + const cacheEntry = this._cachedSources.get(type); + if (cacheEntry !== undefined && cacheEntry.hash === hashDigest) { + // We can reuse the cached source + return cacheEntry.source; + } + + const source = this.generator.generate( + this, + dependencyTemplates, + runtimeTemplate, + type + ); + + const cachedSource = new CachedSource(source); + this._cachedSources.set(type, { + source: cachedSource, + hash: hashDigest + }); + return cachedSource; + } + + originalSource() { + return this._source; + } + + needRebuild(fileTimestamps, contextTimestamps) { + // always try to rebuild in case of an error + if (this.error) return true; + + // always rebuild when module is not cacheable + if (!this.buildInfo.cacheable) return true; + + // Check timestamps of all dependencies + // Missing timestamp -> need rebuild + // Timestamp bigger than buildTimestamp -> need rebuild + for (const file of this.buildInfo.fileDependencies) { + const timestamp = fileTimestamps.get(file); + if (!timestamp) return true; + if (timestamp >= this.buildTimestamp) return true; + } + for (const file of this.buildInfo.contextDependencies) { + const timestamp = contextTimestamps.get(file); + if (!timestamp) return true; + if (timestamp >= this.buildTimestamp) return true; + } + // elsewise -> no rebuild needed + return false; + } + + size() { + return this._source ? this._source.size() : -1; + } + + /** + * @param {Hash} hash the hash used to track dependencies + * @returns {void} + */ + updateHash(hash) { + hash.update(this._buildHash); + super.updateHash(hash); + } +} + +module.exports = NormalModule; diff --git a/node_modules/webpack/lib/NormalModuleFactory.js b/node_modules/webpack/lib/NormalModuleFactory.js index 138b87d18..23ef0ae1d 100644 --- a/node_modules/webpack/lib/NormalModuleFactory.js +++ b/node_modules/webpack/lib/NormalModuleFactory.js @@ -1,292 +1,526 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
- */
-"use strict";
-
-const asyncLib = require("async");
-const Tapable = require("tapable");
-const NormalModule = require("./NormalModule");
-const RawModule = require("./RawModule");
-const Parser = require("./Parser");
-const RuleSet = require("./RuleSet");
-
-function loaderToIdent(data) {
- if(!data.options)
- return data.loader;
- if(typeof data.options === "string")
- return data.loader + "?" + data.options;
- if(typeof data.options !== "object")
- throw new Error("loader options must be string or object");
- if(data.ident)
- return data.loader + "??" + data.ident;
- return data.loader + "?" + JSON.stringify(data.options);
-}
-
-function identToLoaderRequest(resultString) {
- const idx = resultString.indexOf("?");
- let options;
-
- if(idx >= 0) {
- options = resultString.substr(idx + 1);
- resultString = resultString.substr(0, idx);
-
- return {
- loader: resultString,
- options
- };
- } else {
- return {
- loader: resultString
- };
- }
-}
-
-class NormalModuleFactory extends Tapable {
- constructor(context, resolvers, options) {
- super();
- this.resolvers = resolvers;
- this.ruleSet = new RuleSet(options.rules || options.loaders);
- this.cachePredicate = typeof options.unsafeCache === "function" ? options.unsafeCache : Boolean.bind(null, options.unsafeCache);
- this.context = context || "";
- this.parserCache = {};
- this.plugin("factory", () => (result, callback) => {
- let resolver = this.applyPluginsWaterfall0("resolver", null);
-
- // Ignored
- if(!resolver) return callback();
-
- resolver(result, (err, data) => {
- if(err) return callback(err);
-
- // Ignored
- if(!data) return callback();
-
- // direct module
- if(typeof data.source === "function")
- return callback(null, data);
-
- this.applyPluginsAsyncWaterfall("after-resolve", data, (err, result) => {
- if(err) return callback(err);
-
- // Ignored
- if(!result) return callback();
-
- let createdModule = this.applyPluginsBailResult("create-module", result);
- if(!createdModule) {
-
- if(!result.request) {
- return callback(new Error("Empty dependency (no request)"));
- }
-
- createdModule = new NormalModule(
- result.request,
- result.userRequest,
- result.rawRequest,
- result.loaders,
- result.resource,
- result.parser
- );
- }
-
- createdModule = this.applyPluginsWaterfall0("module", createdModule);
-
- return callback(null, createdModule);
- });
- });
- });
- this.plugin("resolver", () => (data, callback) => {
- const contextInfo = data.contextInfo;
- const context = data.context;
- const request = data.request;
-
- const noAutoLoaders = /^-?!/.test(request);
- const noPrePostAutoLoaders = /^!!/.test(request);
- const noPostAutoLoaders = /^-!/.test(request);
- let elements = request.replace(/^-?!+/, "").replace(/!!+/g, "!").split("!");
- let resource = elements.pop();
- elements = elements.map(identToLoaderRequest);
-
- asyncLib.parallel([
- callback => this.resolveRequestArray(contextInfo, context, elements, this.resolvers.loader, callback),
- callback => {
- if(resource === "" || resource[0] === "?")
- return callback(null, {
- resource
- });
-
- this.resolvers.normal.resolve(contextInfo, context, resource, (err, resource, resourceResolveData) => {
- if(err) return callback(err);
- callback(null, {
- resourceResolveData,
- resource
- });
- });
- }
- ], (err, results) => {
- if(err) return callback(err);
- let loaders = results[0];
- const resourceResolveData = results[1].resourceResolveData;
- resource = results[1].resource;
-
- // translate option idents
- try {
- loaders.forEach(item => {
- if(typeof item.options === "string" && /^\?/.test(item.options)) {
- item.options = this.ruleSet.findOptionsByIdent(item.options.substr(1));
- }
- });
- } catch(e) {
- return callback(e);
- }
-
- if(resource === false) {
- // ignored
- return callback(null,
- new RawModule(
- "/* (ignored) */",
- `ignored ${context} ${request}`,
- `${request} (ignored)`
- )
- );
- }
-
- const userRequest = loaders.map(loaderToIdent).concat([resource]).join("!");
-
- let resourcePath = resource;
- let resourceQuery = "";
- const queryIndex = resourcePath.indexOf("?");
- if(queryIndex >= 0) {
- resourceQuery = resourcePath.substr(queryIndex);
- resourcePath = resourcePath.substr(0, queryIndex);
- }
-
- const result = this.ruleSet.exec({
- resource: resourcePath,
- resourceQuery,
- issuer: contextInfo.issuer,
- compiler: contextInfo.compiler
- });
- const settings = {};
- const useLoadersPost = [];
- const useLoaders = [];
- const useLoadersPre = [];
- result.forEach(r => {
- if(r.type === "use") {
- if(r.enforce === "post" && !noPostAutoLoaders && !noPrePostAutoLoaders)
- useLoadersPost.push(r.value);
- else if(r.enforce === "pre" && !noPrePostAutoLoaders)
- useLoadersPre.push(r.value);
- else if(!r.enforce && !noAutoLoaders && !noPrePostAutoLoaders)
- useLoaders.push(r.value);
- } else {
- settings[r.type] = r.value;
- }
- });
- asyncLib.parallel([
- this.resolveRequestArray.bind(this, contextInfo, this.context, useLoadersPost, this.resolvers.loader),
- this.resolveRequestArray.bind(this, contextInfo, this.context, useLoaders, this.resolvers.loader),
- this.resolveRequestArray.bind(this, contextInfo, this.context, useLoadersPre, this.resolvers.loader)
- ], (err, results) => {
- if(err) return callback(err);
- loaders = results[0].concat(loaders, results[1], results[2]);
- process.nextTick(() => {
- callback(null, {
- context: context,
- request: loaders.map(loaderToIdent).concat([resource]).join("!"),
- dependencies: data.dependencies,
- userRequest,
- rawRequest: request,
- loaders,
- resource,
- resourceResolveData,
- parser: this.getParser(settings.parser)
- });
- });
- });
- });
- });
- }
-
- create(data, callback) {
- const dependencies = data.dependencies;
- const cacheEntry = dependencies[0].__NormalModuleFactoryCache;
- if(cacheEntry) return callback(null, cacheEntry);
- const context = data.context || this.context;
- const request = dependencies[0].request;
- const contextInfo = data.contextInfo || {};
- this.applyPluginsAsyncWaterfall("before-resolve", {
- contextInfo,
- context,
- request,
- dependencies
- }, (err, result) => {
- if(err) return callback(err);
-
- // Ignored
- if(!result) return callback();
-
- const factory = this.applyPluginsWaterfall0("factory", null);
-
- // Ignored
- if(!factory) return callback();
-
- factory(result, (err, module) => {
- if(err) return callback(err);
-
- if(module && this.cachePredicate(module)) {
- dependencies.forEach(d => d.__NormalModuleFactoryCache = module);
- }
-
- callback(null, module);
- });
- });
- }
-
- resolveRequestArray(contextInfo, context, array, resolver, callback) {
- if(array.length === 0) return callback(null, []);
- asyncLib.map(array, (item, callback) => {
- resolver.resolve(contextInfo, context, item.loader, (err, result) => {
- if(err && /^[^/]*$/.test(item.loader) && !/-loader$/.test(item.loader)) {
- return resolver.resolve(contextInfo, context, item.loader + "-loader", err2 => {
- if(!err2) {
- err.message = err.message + "\n" +
- "BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix when using loaders.\n" +
- ` You need to specify '${item.loader}-loader' instead of '${item.loader}',\n` +
- " see https://webpack.js.org/guides/migrating/#automatic-loader-module-name-extension-removed";
- }
- callback(err);
- });
- }
- if(err) return callback(err);
-
- const optionsOnly = item.options ? {
- options: item.options
- } : undefined;
- return callback(null, Object.assign({}, item, identToLoaderRequest(result), optionsOnly));
- });
- }, callback);
- }
-
- getParser(parserOptions) {
- let ident = "null";
- if(parserOptions) {
- if(parserOptions.ident)
- ident = parserOptions.ident;
- else
- ident = JSON.stringify(parserOptions);
- }
- const parser = this.parserCache[ident];
- if(parser)
- return parser;
- return this.parserCache[ident] = this.createParser(parserOptions);
- }
-
- createParser(parserOptions) {
- const parser = new Parser();
- this.applyPlugins2("parser", parser, parserOptions || {});
- return parser;
- }
-}
-
-module.exports = NormalModuleFactory;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra + */ +"use strict"; + +const path = require("path"); +const asyncLib = require("neo-async"); +const { + Tapable, + AsyncSeriesWaterfallHook, + SyncWaterfallHook, + SyncBailHook, + SyncHook, + HookMap +} = require("tapable"); +const NormalModule = require("./NormalModule"); +const RawModule = require("./RawModule"); +const RuleSet = require("./RuleSet"); +const cachedMerge = require("./util/cachedMerge"); + +const EMPTY_RESOLVE_OPTIONS = {}; + +const MATCH_RESOURCE_REGEX = /^([^!]+)!=!/; + +const loaderToIdent = data => { + if (!data.options) { + return data.loader; + } + if (typeof data.options === "string") { + return data.loader + "?" + data.options; + } + if (typeof data.options !== "object") { + throw new Error("loader options must be string or object"); + } + if (data.ident) { + return data.loader + "??" + data.ident; + } + return data.loader + "?" + JSON.stringify(data.options); +}; + +const identToLoaderRequest = resultString => { + const idx = resultString.indexOf("?"); + if (idx >= 0) { + const loader = resultString.substr(0, idx); + const options = resultString.substr(idx + 1); + return { + loader, + options + }; + } else { + return { + loader: resultString, + options: undefined + }; + } +}; + +const dependencyCache = new WeakMap(); + +class NormalModuleFactory extends Tapable { + constructor(context, resolverFactory, options) { + super(); + this.hooks = { + resolver: new SyncWaterfallHook(["resolver"]), + factory: new SyncWaterfallHook(["factory"]), + beforeResolve: new AsyncSeriesWaterfallHook(["data"]), + afterResolve: new AsyncSeriesWaterfallHook(["data"]), + createModule: new SyncBailHook(["data"]), + module: new SyncWaterfallHook(["module", "data"]), + createParser: new HookMap(() => new SyncBailHook(["parserOptions"])), + parser: new HookMap(() => new SyncHook(["parser", "parserOptions"])), + createGenerator: new HookMap( + () => new SyncBailHook(["generatorOptions"]) + ), + generator: new HookMap( + () => new SyncHook(["generator", "generatorOptions"]) + ) + }; + this._pluginCompat.tap("NormalModuleFactory", options => { + switch (options.name) { + case "before-resolve": + case "after-resolve": + options.async = true; + break; + case "parser": + this.hooks.parser + .for("javascript/auto") + .tap(options.fn.name || "unnamed compat plugin", options.fn); + return true; + } + let match; + match = /^parser (.+)$/.exec(options.name); + if (match) { + this.hooks.parser + .for(match[1]) + .tap( + options.fn.name || "unnamed compat plugin", + options.fn.bind(this) + ); + return true; + } + match = /^create-parser (.+)$/.exec(options.name); + if (match) { + this.hooks.createParser + .for(match[1]) + .tap( + options.fn.name || "unnamed compat plugin", + options.fn.bind(this) + ); + return true; + } + }); + this.resolverFactory = resolverFactory; + this.ruleSet = new RuleSet(options.defaultRules.concat(options.rules)); + this.cachePredicate = + typeof options.unsafeCache === "function" + ? options.unsafeCache + : Boolean.bind(null, options.unsafeCache); + this.context = context || ""; + this.parserCache = Object.create(null); + this.generatorCache = Object.create(null); + this.hooks.factory.tap("NormalModuleFactory", () => (result, callback) => { + let resolver = this.hooks.resolver.call(null); + + // Ignored + if (!resolver) return callback(); + + resolver(result, (err, data) => { + if (err) return callback(err); + + // Ignored + if (!data) return callback(); + + // direct module + if (typeof data.source === "function") return callback(null, data); + + this.hooks.afterResolve.callAsync(data, (err, result) => { + if (err) return callback(err); + + // Ignored + if (!result) return callback(); + + let createdModule = this.hooks.createModule.call(result); + if (!createdModule) { + if (!result.request) { + return callback(new Error("Empty dependency (no request)")); + } + + createdModule = new NormalModule(result); + } + + createdModule = this.hooks.module.call(createdModule, result); + + return callback(null, createdModule); + }); + }); + }); + this.hooks.resolver.tap("NormalModuleFactory", () => (data, callback) => { + const contextInfo = data.contextInfo; + const context = data.context; + const request = data.request; + + const loaderResolver = this.getResolver("loader"); + const normalResolver = this.getResolver("normal", data.resolveOptions); + + let matchResource = undefined; + let requestWithoutMatchResource = request; + const matchResourceMatch = MATCH_RESOURCE_REGEX.exec(request); + if (matchResourceMatch) { + matchResource = matchResourceMatch[1]; + if (/^\.\.?\//.test(matchResource)) { + matchResource = path.join(context, matchResource); + } + requestWithoutMatchResource = request.substr( + matchResourceMatch[0].length + ); + } + + const noPreAutoLoaders = requestWithoutMatchResource.startsWith("-!"); + const noAutoLoaders = + noPreAutoLoaders || requestWithoutMatchResource.startsWith("!"); + const noPrePostAutoLoaders = requestWithoutMatchResource.startsWith("!!"); + let elements = requestWithoutMatchResource + .replace(/^-?!+/, "") + .replace(/!!+/g, "!") + .split("!"); + let resource = elements.pop(); + elements = elements.map(identToLoaderRequest); + + asyncLib.parallel( + [ + callback => + this.resolveRequestArray( + contextInfo, + context, + elements, + loaderResolver, + callback + ), + callback => { + if (resource === "" || resource[0] === "?") { + return callback(null, { + resource + }); + } + + normalResolver.resolve( + contextInfo, + context, + resource, + {}, + (err, resource, resourceResolveData) => { + if (err) return callback(err); + callback(null, { + resourceResolveData, + resource + }); + } + ); + } + ], + (err, results) => { + if (err) return callback(err); + let loaders = results[0]; + const resourceResolveData = results[1].resourceResolveData; + resource = results[1].resource; + + // translate option idents + try { + for (const item of loaders) { + if (typeof item.options === "string" && item.options[0] === "?") { + const ident = item.options.substr(1); + item.options = this.ruleSet.findOptionsByIdent(ident); + item.ident = ident; + } + } + } catch (e) { + return callback(e); + } + + if (resource === false) { + // ignored + return callback( + null, + new RawModule( + "/* (ignored) */", + `ignored ${context} ${request}`, + `${request} (ignored)` + ) + ); + } + + const userRequest = + (matchResource !== undefined ? `${matchResource}!=!` : "") + + loaders + .map(loaderToIdent) + .concat([resource]) + .join("!"); + + let resourcePath = + matchResource !== undefined ? matchResource : resource; + let resourceQuery = ""; + const queryIndex = resourcePath.indexOf("?"); + if (queryIndex >= 0) { + resourceQuery = resourcePath.substr(queryIndex); + resourcePath = resourcePath.substr(0, queryIndex); + } + + const result = this.ruleSet.exec({ + resource: resourcePath, + realResource: + matchResource !== undefined + ? resource.replace(/\?.*/, "") + : resourcePath, + resourceQuery, + issuer: contextInfo.issuer, + compiler: contextInfo.compiler + }); + const settings = {}; + const useLoadersPost = []; + const useLoaders = []; + const useLoadersPre = []; + for (const r of result) { + if (r.type === "use") { + if (r.enforce === "post" && !noPrePostAutoLoaders) { + useLoadersPost.push(r.value); + } else if ( + r.enforce === "pre" && + !noPreAutoLoaders && + !noPrePostAutoLoaders + ) { + useLoadersPre.push(r.value); + } else if ( + !r.enforce && + !noAutoLoaders && + !noPrePostAutoLoaders + ) { + useLoaders.push(r.value); + } + } else if ( + typeof r.value === "object" && + r.value !== null && + typeof settings[r.type] === "object" && + settings[r.type] !== null + ) { + settings[r.type] = cachedMerge(settings[r.type], r.value); + } else { + settings[r.type] = r.value; + } + } + asyncLib.parallel( + [ + this.resolveRequestArray.bind( + this, + contextInfo, + this.context, + useLoadersPost, + loaderResolver + ), + this.resolveRequestArray.bind( + this, + contextInfo, + this.context, + useLoaders, + loaderResolver + ), + this.resolveRequestArray.bind( + this, + contextInfo, + this.context, + useLoadersPre, + loaderResolver + ) + ], + (err, results) => { + if (err) return callback(err); + loaders = results[0].concat(loaders, results[1], results[2]); + process.nextTick(() => { + const type = settings.type; + const resolveOptions = settings.resolve; + callback(null, { + context: context, + request: loaders + .map(loaderToIdent) + .concat([resource]) + .join("!"), + dependencies: data.dependencies, + userRequest, + rawRequest: request, + loaders, + resource, + matchResource, + resourceResolveData, + settings, + type, + parser: this.getParser(type, settings.parser), + generator: this.getGenerator(type, settings.generator), + resolveOptions + }); + }); + } + ); + } + ); + }); + } + + create(data, callback) { + const dependencies = data.dependencies; + const cacheEntry = dependencyCache.get(dependencies[0]); + if (cacheEntry) return callback(null, cacheEntry); + const context = data.context || this.context; + const resolveOptions = data.resolveOptions || EMPTY_RESOLVE_OPTIONS; + const request = dependencies[0].request; + const contextInfo = data.contextInfo || {}; + this.hooks.beforeResolve.callAsync( + { + contextInfo, + resolveOptions, + context, + request, + dependencies + }, + (err, result) => { + if (err) return callback(err); + + // Ignored + if (!result) return callback(); + + const factory = this.hooks.factory.call(null); + + // Ignored + if (!factory) return callback(); + + factory(result, (err, module) => { + if (err) return callback(err); + + if (module && this.cachePredicate(module)) { + for (const d of dependencies) { + dependencyCache.set(d, module); + } + } + + callback(null, module); + }); + } + ); + } + + resolveRequestArray(contextInfo, context, array, resolver, callback) { + if (array.length === 0) return callback(null, []); + asyncLib.map( + array, + (item, callback) => { + resolver.resolve( + contextInfo, + context, + item.loader, + {}, + (err, result) => { + if ( + err && + /^[^/]*$/.test(item.loader) && + !/-loader$/.test(item.loader) + ) { + return resolver.resolve( + contextInfo, + context, + item.loader + "-loader", + {}, + err2 => { + if (!err2) { + err.message = + err.message + + "\n" + + "BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix when using loaders.\n" + + ` You need to specify '${ + item.loader + }-loader' instead of '${item.loader}',\n` + + " see https://webpack.js.org/migrate/3/#automatic-loader-module-name-extension-removed"; + } + callback(err); + } + ); + } + if (err) return callback(err); + + const optionsOnly = item.options + ? { + options: item.options + } + : undefined; + return callback( + null, + Object.assign({}, item, identToLoaderRequest(result), optionsOnly) + ); + } + ); + }, + callback + ); + } + + getParser(type, parserOptions) { + let ident = type; + if (parserOptions) { + if (parserOptions.ident) { + ident = `${type}|${parserOptions.ident}`; + } else { + ident = JSON.stringify([type, parserOptions]); + } + } + if (ident in this.parserCache) { + return this.parserCache[ident]; + } + return (this.parserCache[ident] = this.createParser(type, parserOptions)); + } + + createParser(type, parserOptions = {}) { + const parser = this.hooks.createParser.for(type).call(parserOptions); + if (!parser) { + throw new Error(`No parser registered for ${type}`); + } + this.hooks.parser.for(type).call(parser, parserOptions); + return parser; + } + + getGenerator(type, generatorOptions) { + let ident = type; + if (generatorOptions) { + if (generatorOptions.ident) { + ident = `${type}|${generatorOptions.ident}`; + } else { + ident = JSON.stringify([type, generatorOptions]); + } + } + if (ident in this.generatorCache) { + return this.generatorCache[ident]; + } + return (this.generatorCache[ident] = this.createGenerator( + type, + generatorOptions + )); + } + + createGenerator(type, generatorOptions = {}) { + const generator = this.hooks.createGenerator + .for(type) + .call(generatorOptions); + if (!generator) { + throw new Error(`No generator registered for ${type}`); + } + this.hooks.generator.for(type).call(generator, generatorOptions); + return generator; + } + + getResolver(type, resolveOptions) { + return this.resolverFactory.get( + type, + resolveOptions || EMPTY_RESOLVE_OPTIONS + ); + } +} + +module.exports = NormalModuleFactory; diff --git a/node_modules/webpack/lib/NormalModuleReplacementPlugin.js b/node_modules/webpack/lib/NormalModuleReplacementPlugin.js index 46a662d68..d4f23a58b 100644 --- a/node_modules/webpack/lib/NormalModuleReplacementPlugin.js +++ b/node_modules/webpack/lib/NormalModuleReplacementPlugin.js @@ -1,45 +1,51 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const path = require("path");
-
-class NormalModuleReplacementPlugin {
- constructor(resourceRegExp, newResource) {
- this.resourceRegExp = resourceRegExp;
- this.newResource = newResource;
- }
-
- apply(compiler) {
- const resourceRegExp = this.resourceRegExp;
- const newResource = this.newResource;
- compiler.plugin("normal-module-factory", (nmf) => {
- nmf.plugin("before-resolve", (result, callback) => {
- if(!result) return callback();
- if(resourceRegExp.test(result.request)) {
- if(typeof newResource === "function") {
- newResource(result);
- } else {
- result.request = newResource;
- }
- }
- return callback(null, result);
- });
- nmf.plugin("after-resolve", (result, callback) => {
- if(!result) return callback();
- if(resourceRegExp.test(result.resource)) {
- if(typeof newResource === "function") {
- newResource(result);
- } else {
- result.resource = path.resolve(path.dirname(result.resource), newResource);
- }
- }
- return callback(null, result);
- });
- });
- }
-}
-
-module.exports = NormalModuleReplacementPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const path = require("path"); + +class NormalModuleReplacementPlugin { + constructor(resourceRegExp, newResource) { + this.resourceRegExp = resourceRegExp; + this.newResource = newResource; + } + + apply(compiler) { + const resourceRegExp = this.resourceRegExp; + const newResource = this.newResource; + compiler.hooks.normalModuleFactory.tap( + "NormalModuleReplacementPlugin", + nmf => { + nmf.hooks.beforeResolve.tap("NormalModuleReplacementPlugin", result => { + if (!result) return; + if (resourceRegExp.test(result.request)) { + if (typeof newResource === "function") { + newResource(result); + } else { + result.request = newResource; + } + } + return result; + }); + nmf.hooks.afterResolve.tap("NormalModuleReplacementPlugin", result => { + if (!result) return; + if (resourceRegExp.test(result.resource)) { + if (typeof newResource === "function") { + newResource(result); + } else { + result.resource = path.resolve( + path.dirname(result.resource), + newResource + ); + } + } + return result; + }); + } + ); + } +} + +module.exports = NormalModuleReplacementPlugin; diff --git a/node_modules/webpack/lib/NullFactory.js b/node_modules/webpack/lib/NullFactory.js index 9ff4cb58e..90ede1fe3 100644 --- a/node_modules/webpack/lib/NullFactory.js +++ b/node_modules/webpack/lib/NullFactory.js @@ -1,12 +1,12 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-class NullFactory {
- create(data, callback) {
- return callback();
- }
-}
-module.exports = NullFactory;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +class NullFactory { + create(data, callback) { + return callback(); + } +} +module.exports = NullFactory; diff --git a/node_modules/webpack/lib/OptionsApply.js b/node_modules/webpack/lib/OptionsApply.js index 022506360..3b1ec3164 100644 --- a/node_modules/webpack/lib/OptionsApply.js +++ b/node_modules/webpack/lib/OptionsApply.js @@ -1,10 +1,10 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-class OptionsApply {
- process(options, compiler) {}
-}
-module.exports = OptionsApply;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +class OptionsApply { + process(options, compiler) {} +} +module.exports = OptionsApply; diff --git a/node_modules/webpack/lib/OptionsDefaulter.js b/node_modules/webpack/lib/OptionsDefaulter.js index 42120689d..cad07ea06 100644 --- a/node_modules/webpack/lib/OptionsDefaulter.js +++ b/node_modules/webpack/lib/OptionsDefaulter.js @@ -1,73 +1,83 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-function getProperty(obj, name) {
- name = name.split(".");
- for(let i = 0; i < name.length - 1; i++) {
- obj = obj[name[i]];
- if(typeof obj !== "object" || !obj) return;
- }
- return obj[name.pop()];
-}
-
-function setProperty(obj, name, value) {
- name = name.split(".");
- for(let i = 0; i < name.length - 1; i++) {
- if(typeof obj[name[i]] !== "object" && typeof obj[name[i]] !== "undefined") return;
- if(!obj[name[i]]) obj[name[i]] = {};
- obj = obj[name[i]];
- }
- obj[name.pop()] = value;
-}
-
-class OptionsDefaulter {
- constructor() {
- this.defaults = {};
- this.config = {};
- }
-
- process(options) {
- // TODO: change this for webpack 4: options = Object.assign({}, options);
- for(let name in this.defaults) {
- switch(this.config[name]) {
- case undefined:
- if(getProperty(options, name) === undefined)
- setProperty(options, name, this.defaults[name]);
- break;
- case "call":
- setProperty(options, name, this.defaults[name].call(this, getProperty(options, name), options), options);
- break;
- case "make":
- if(getProperty(options, name) === undefined)
- setProperty(options, name, this.defaults[name].call(this, options), options);
- break;
- case "append":
- {
- let oldValue = getProperty(options, name);
- if(!Array.isArray(oldValue)) oldValue = [];
- oldValue.push.apply(oldValue, this.defaults[name]);
- setProperty(options, name, oldValue);
- break;
- }
- default:
- throw new Error("OptionsDefaulter cannot process " + this.config[name]);
- }
- }
- // TODO: change this for webpack 4: return options;
- }
-
- set(name, config, def) {
- if(arguments.length === 3) {
- this.defaults[name] = def;
- this.config[name] = config;
- } else {
- this.defaults[name] = config;
- delete this.config[name];
- }
- }
-}
-
-module.exports = OptionsDefaulter;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const getProperty = (obj, name) => { + name = name.split("."); + for (let i = 0; i < name.length - 1; i++) { + obj = obj[name[i]]; + if (typeof obj !== "object" || !obj || Array.isArray(obj)) return; + } + return obj[name.pop()]; +}; + +const setProperty = (obj, name, value) => { + name = name.split("."); + for (let i = 0; i < name.length - 1; i++) { + if (typeof obj[name[i]] !== "object" && obj[name[i]] !== undefined) return; + if (Array.isArray(obj[name[i]])) return; + if (!obj[name[i]]) obj[name[i]] = {}; + obj = obj[name[i]]; + } + obj[name.pop()] = value; +}; + +class OptionsDefaulter { + constructor() { + this.defaults = {}; + this.config = {}; + } + + process(options) { + options = Object.assign({}, options); + for (let name in this.defaults) { + switch (this.config[name]) { + case undefined: + if (getProperty(options, name) === undefined) { + setProperty(options, name, this.defaults[name]); + } + break; + case "call": + setProperty( + options, + name, + this.defaults[name].call(this, getProperty(options, name), options) + ); + break; + case "make": + if (getProperty(options, name) === undefined) { + setProperty(options, name, this.defaults[name].call(this, options)); + } + break; + case "append": { + let oldValue = getProperty(options, name); + if (!Array.isArray(oldValue)) { + oldValue = []; + } + oldValue.push(...this.defaults[name]); + setProperty(options, name, oldValue); + break; + } + default: + throw new Error( + "OptionsDefaulter cannot process " + this.config[name] + ); + } + } + return options; + } + + set(name, config, def) { + if (def !== undefined) { + this.defaults[name] = def; + this.config[name] = config; + } else { + this.defaults[name] = config; + delete this.config[name]; + } + } +} + +module.exports = OptionsDefaulter; diff --git a/node_modules/webpack/lib/Parser.js b/node_modules/webpack/lib/Parser.js index 3150f847a..787f67d61 100644 --- a/node_modules/webpack/lib/Parser.js +++ b/node_modules/webpack/lib/Parser.js @@ -1,1462 +1,2202 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-// Syntax: https://developer.mozilla.org/en/SpiderMonkey/Parser_API
-
-const acorn = require("acorn-dynamic-import").default;
-const Tapable = require("tapable");
-const json5 = require("json5");
-const BasicEvaluatedExpression = require("./BasicEvaluatedExpression");
-
-function joinRanges(startRange, endRange) {
- if(!endRange) return startRange;
- if(!startRange) return endRange;
- return [startRange[0], endRange[1]];
-}
-
-const ECMA_VERSION = 2017;
-
-const POSSIBLE_AST_OPTIONS = [{
- ranges: true,
- locations: true,
- ecmaVersion: ECMA_VERSION,
- sourceType: "module",
- plugins: {
- dynamicImport: true
- }
-}, {
- ranges: true,
- locations: true,
- ecmaVersion: ECMA_VERSION,
- sourceType: "script",
- plugins: {
- dynamicImport: true
- }
-}];
-
-class Parser extends Tapable {
- constructor(options) {
- super();
- this.options = options;
- this.scope = undefined;
- this.state = undefined;
- this.comments = undefined;
- this.initializeEvaluating();
- }
-
- initializeEvaluating() {
- this.plugin("evaluate Literal", expr => {
- switch(typeof expr.value) {
- case "number":
- return new BasicEvaluatedExpression().setNumber(expr.value).setRange(expr.range);
- case "string":
- return new BasicEvaluatedExpression().setString(expr.value).setRange(expr.range);
- case "boolean":
- return new BasicEvaluatedExpression().setBoolean(expr.value).setRange(expr.range);
- }
- if(expr.value === null)
- return new BasicEvaluatedExpression().setNull().setRange(expr.range);
- if(expr.value instanceof RegExp)
- return new BasicEvaluatedExpression().setRegExp(expr.value).setRange(expr.range);
- });
- this.plugin("evaluate LogicalExpression", function(expr) {
- let left;
- let leftAsBool;
- let right;
- if(expr.operator === "&&") {
- left = this.evaluateExpression(expr.left);
- leftAsBool = left && left.asBool();
- if(leftAsBool === false) return left.setRange(expr.range);
- if(leftAsBool !== true) return;
- right = this.evaluateExpression(expr.right);
- return right.setRange(expr.range);
- } else if(expr.operator === "||") {
- left = this.evaluateExpression(expr.left);
- leftAsBool = left && left.asBool();
- if(leftAsBool === true) return left.setRange(expr.range);
- if(leftAsBool !== false) return;
- right = this.evaluateExpression(expr.right);
- return right.setRange(expr.range);
- }
- });
- this.plugin("evaluate BinaryExpression", function(expr) {
- let left;
- let right;
- let res;
- if(expr.operator === "+") {
- left = this.evaluateExpression(expr.left);
- right = this.evaluateExpression(expr.right);
- if(!left || !right) return;
- res = new BasicEvaluatedExpression();
- if(left.isString()) {
- if(right.isString()) {
- res.setString(left.string + right.string);
- } else if(right.isNumber()) {
- res.setString(left.string + right.number);
- } else if(right.isWrapped() && right.prefix && right.prefix.isString()) {
- res.setWrapped(
- new BasicEvaluatedExpression()
- .setString(left.string + right.prefix.string)
- .setRange(joinRanges(left.range, right.prefix.range)),
- right.postfix);
- } else if(right.isWrapped()) {
- res.setWrapped(
- new BasicEvaluatedExpression()
- .setString(left.string)
- .setRange(left.range),
- right.postfix);
- } else {
- res.setWrapped(left, null);
- }
- } else if(left.isNumber()) {
- if(right.isString()) {
- res.setString(left.number + right.string);
- } else if(right.isNumber()) {
- res.setNumber(left.number + right.number);
- }
- } else if(left.isWrapped()) {
- if(left.postfix && left.postfix.isString() && right.isString()) {
- res.setWrapped(left.prefix,
- new BasicEvaluatedExpression()
- .setString(left.postfix.string + right.string)
- .setRange(joinRanges(left.postfix.range, right.range))
- );
- } else if(left.postfix && left.postfix.isString() && right.isNumber()) {
- res.setWrapped(left.prefix,
- new BasicEvaluatedExpression()
- .setString(left.postfix.string + right.number)
- .setRange(joinRanges(left.postfix.range, right.range))
- );
- } else if(right.isString()) {
- res.setWrapped(left.prefix, right);
- } else if(right.isNumber()) {
- res.setWrapped(left.prefix,
- new BasicEvaluatedExpression()
- .setString(right.number + "")
- .setRange(right.range));
- } else {
- res.setWrapped(left.prefix, new BasicEvaluatedExpression());
- }
- } else {
- if(right.isString()) {
- res.setWrapped(null, right);
- }
- }
- res.setRange(expr.range);
- return res;
- } else if(expr.operator === "-") {
- left = this.evaluateExpression(expr.left);
- right = this.evaluateExpression(expr.right);
- if(!left || !right) return;
- if(!left.isNumber() || !right.isNumber()) return;
- res = new BasicEvaluatedExpression();
- res.setNumber(left.number - right.number);
- res.setRange(expr.range);
- return res;
- } else if(expr.operator === "*") {
- left = this.evaluateExpression(expr.left);
- right = this.evaluateExpression(expr.right);
- if(!left || !right) return;
- if(!left.isNumber() || !right.isNumber()) return;
- res = new BasicEvaluatedExpression();
- res.setNumber(left.number * right.number);
- res.setRange(expr.range);
- return res;
- } else if(expr.operator === "/") {
- left = this.evaluateExpression(expr.left);
- right = this.evaluateExpression(expr.right);
- if(!left || !right) return;
- if(!left.isNumber() || !right.isNumber()) return;
- res = new BasicEvaluatedExpression();
- res.setNumber(left.number / right.number);
- res.setRange(expr.range);
- return res;
- } else if(expr.operator === "==" || expr.operator === "===") {
- left = this.evaluateExpression(expr.left);
- right = this.evaluateExpression(expr.right);
- if(!left || !right) return;
- res = new BasicEvaluatedExpression();
- res.setRange(expr.range);
- if(left.isString() && right.isString()) {
- return res.setBoolean(left.string === right.string);
- } else if(left.isNumber() && right.isNumber()) {
- return res.setBoolean(left.number === right.number);
- } else if(left.isBoolean() && right.isBoolean()) {
- return res.setBoolean(left.bool === right.bool);
- }
- } else if(expr.operator === "!=" || expr.operator === "!==") {
- left = this.evaluateExpression(expr.left);
- right = this.evaluateExpression(expr.right);
- if(!left || !right) return;
- res = new BasicEvaluatedExpression();
- res.setRange(expr.range);
- if(left.isString() && right.isString()) {
- return res.setBoolean(left.string !== right.string);
- } else if(left.isNumber() && right.isNumber()) {
- return res.setBoolean(left.number !== right.number);
- } else if(left.isBoolean() && right.isBoolean()) {
- return res.setBoolean(left.bool !== right.bool);
- }
- }
- });
- this.plugin("evaluate UnaryExpression", function(expr) {
- if(expr.operator === "typeof") {
- let res;
- let name;
- if(expr.argument.type === "Identifier") {
- name = this.scope.renames["$" + expr.argument.name] || expr.argument.name;
- if(this.scope.definitions.indexOf(name) === -1) {
- res = this.applyPluginsBailResult1("evaluate typeof " + name, expr);
- if(res !== undefined) return res;
- }
- }
- if(expr.argument.type === "MemberExpression") {
- const exprName = this.getNameForExpression(expr.argument);
- if(exprName && exprName.free) {
- res = this.applyPluginsBailResult1("evaluate typeof " + exprName.name, expr);
- if(res !== undefined) return res;
- }
- }
- if(expr.argument.type === "FunctionExpression") {
- return new BasicEvaluatedExpression().setString("function").setRange(expr.range);
- }
- const arg = this.evaluateExpression(expr.argument);
- if(arg.isString() || arg.isWrapped()) return new BasicEvaluatedExpression().setString("string").setRange(expr.range);
- else if(arg.isNumber()) return new BasicEvaluatedExpression().setString("number").setRange(expr.range);
- else if(arg.isBoolean()) return new BasicEvaluatedExpression().setString("boolean").setRange(expr.range);
- else if(arg.isArray() || arg.isConstArray() || arg.isRegExp()) return new BasicEvaluatedExpression().setString("object").setRange(expr.range);
- } else if(expr.operator === "!") {
- const argument = this.evaluateExpression(expr.argument);
- if(!argument) return;
- if(argument.isBoolean()) {
- return new BasicEvaluatedExpression().setBoolean(!argument.bool).setRange(expr.range);
- } else if(argument.isTruthy()) {
- return new BasicEvaluatedExpression().setBoolean(false).setRange(expr.range);
- } else if(argument.isFalsy()) {
- return new BasicEvaluatedExpression().setBoolean(true).setRange(expr.range);
- } else if(argument.isString()) {
- return new BasicEvaluatedExpression().setBoolean(!argument.string).setRange(expr.range);
- } else if(argument.isNumber()) {
- return new BasicEvaluatedExpression().setBoolean(!argument.number).setRange(expr.range);
- }
- }
- });
- this.plugin("evaluate typeof undefined", function(expr) {
- return new BasicEvaluatedExpression().setString("undefined").setRange(expr.range);
- });
- this.plugin("evaluate Identifier", function(expr) {
- const name = this.scope.renames["$" + expr.name] || expr.name;
- if(this.scope.definitions.indexOf(expr.name) === -1) {
- const result = this.applyPluginsBailResult1("evaluate Identifier " + name, expr);
- if(result) return result;
- return new BasicEvaluatedExpression().setIdentifier(name).setRange(expr.range);
- } else {
- return this.applyPluginsBailResult1("evaluate defined Identifier " + name, expr);
- }
- });
- this.plugin("evaluate ThisExpression", function(expr) {
- const name = this.scope.renames.$this;
- if(name) {
- const result = this.applyPluginsBailResult1("evaluate Identifier " + name, expr);
- if(result) return result;
- return new BasicEvaluatedExpression().setIdentifier(name).setRange(expr.range);
- }
- });
- this.plugin("evaluate MemberExpression", function(expression) {
- let exprName = this.getNameForExpression(expression);
- if(exprName) {
- if(exprName.free) {
- const result = this.applyPluginsBailResult1("evaluate Identifier " + exprName.name, expression);
- if(result) return result;
- return new BasicEvaluatedExpression().setIdentifier(exprName.name).setRange(expression.range);
- } else {
- return this.applyPluginsBailResult1("evaluate defined Identifier " + exprName.name, expression);
- }
- }
- });
- this.plugin("evaluate CallExpression", function(expr) {
- if(expr.callee.type !== "MemberExpression") return;
- if(expr.callee.property.type !== (expr.callee.computed ? "Literal" : "Identifier")) return;
- const param = this.evaluateExpression(expr.callee.object);
- if(!param) return;
- const property = expr.callee.property.name || expr.callee.property.value;
- return this.applyPluginsBailResult("evaluate CallExpression ." + property, expr, param);
- });
- this.plugin("evaluate CallExpression .replace", function(expr, param) {
- if(!param.isString()) return;
- if(expr.arguments.length !== 2) return;
- let arg1 = this.evaluateExpression(expr.arguments[0]);
- let arg2 = this.evaluateExpression(expr.arguments[1]);
- if(!arg1.isString() && !arg1.isRegExp()) return;
- arg1 = arg1.regExp || arg1.string;
- if(!arg2.isString()) return;
- arg2 = arg2.string;
- return new BasicEvaluatedExpression().setString(param.string.replace(arg1, arg2)).setRange(expr.range);
- });
- ["substr", "substring"].forEach(fn => {
- this.plugin("evaluate CallExpression ." + fn, function(expr, param) {
- if(!param.isString()) return;
- let arg1;
- let result, str = param.string;
- switch(expr.arguments.length) {
- case 1:
- arg1 = this.evaluateExpression(expr.arguments[0]);
- if(!arg1.isNumber()) return;
- result = str[fn](arg1.number);
- break;
- case 2:
- {
- arg1 = this.evaluateExpression(expr.arguments[0]);
- const arg2 = this.evaluateExpression(expr.arguments[1]);
- if(!arg1.isNumber()) return;
- if(!arg2.isNumber()) return;
- result = str[fn](arg1.number, arg2.number);
- break;
- }
- default:
- return;
- }
- return new BasicEvaluatedExpression().setString(result).setRange(expr.range);
- });
- });
-
- /**
- * @param {string} kind "cooked" | "raw"
- * @param {any[]} quasis quasis
- * @param {any[]} expressions expressions
- * @return {BasicEvaluatedExpression[]} Simplified template
- */
- function getSimplifiedTemplateResult(kind, quasis, expressions) {
- const parts = [];
-
- for(let i = 0; i < quasis.length; i++) {
- parts.push(new BasicEvaluatedExpression().setString(quasis[i].value[kind]).setRange(quasis[i].range));
-
- if(i > 0) {
- const prevExpr = parts[parts.length - 2],
- lastExpr = parts[parts.length - 1];
- const expr = this.evaluateExpression(expressions[i - 1]);
- if(!(expr.isString() || expr.isNumber())) continue;
-
- prevExpr.setString(prevExpr.string + (expr.isString() ? expr.string : expr.number) + lastExpr.string);
- prevExpr.setRange([prevExpr.range[0], lastExpr.range[1]]);
- parts.pop();
- }
- }
- return parts;
- }
-
- this.plugin("evaluate TemplateLiteral", function(node) {
- const parts = getSimplifiedTemplateResult.call(this, "cooked", node.quasis, node.expressions);
- if(parts.length === 1) {
- return parts[0].setRange(node.range);
- }
- return new BasicEvaluatedExpression().setTemplateString(parts).setRange(node.range);
- });
- this.plugin("evaluate TaggedTemplateExpression", function(node) {
- if(this.evaluateExpression(node.tag).identifier !== "String.raw") return;
- const parts = getSimplifiedTemplateResult.call(this, "raw", node.quasi.quasis, node.quasi.expressions);
- return new BasicEvaluatedExpression().setTemplateString(parts).setRange(node.range);
- });
-
- this.plugin("evaluate CallExpression .concat", function(expr, param) {
- if(!param.isString() && !param.isWrapped()) return;
-
- let stringSuffix = null;
- let hasUnknownParams = false;
- for(let i = expr.arguments.length - 1; i >= 0; i--) {
- const argExpr = this.evaluateExpression(expr.arguments[i]);
- if(!argExpr.isString() && !argExpr.isNumber()) {
- hasUnknownParams = true;
- break;
- }
-
- const value = argExpr.isString() ? argExpr.string : "" + argExpr.number;
-
- const newString = value + (stringSuffix ? stringSuffix.string : "");
- const newRange = [argExpr.range[0], (stringSuffix || argExpr).range[1]];
- stringSuffix = new BasicEvaluatedExpression().setString(newString).setRange(newRange);
- }
-
- if(hasUnknownParams) {
- const prefix = param.isString() ? param : param.prefix;
- return new BasicEvaluatedExpression().setWrapped(prefix, stringSuffix).setRange(expr.range);
- } else if(param.isWrapped()) {
- const postfix = stringSuffix || param.postfix;
- return new BasicEvaluatedExpression().setWrapped(param.prefix, postfix).setRange(expr.range);
- } else {
- const newString = param.string + (stringSuffix ? stringSuffix.string : "");
- return new BasicEvaluatedExpression().setString(newString).setRange(expr.range);
- }
- });
- this.plugin("evaluate CallExpression .split", function(expr, param) {
- if(!param.isString()) return;
- if(expr.arguments.length !== 1) return;
- let result;
- const arg = this.evaluateExpression(expr.arguments[0]);
- if(arg.isString()) {
- result = param.string.split(arg.string);
- } else if(arg.isRegExp()) {
- result = param.string.split(arg.regExp);
- } else return;
- return new BasicEvaluatedExpression().setArray(result).setRange(expr.range);
- });
- this.plugin("evaluate ConditionalExpression", function(expr) {
- const condition = this.evaluateExpression(expr.test);
- const conditionValue = condition.asBool();
- let res;
- if(conditionValue === undefined) {
- const consequent = this.evaluateExpression(expr.consequent);
- const alternate = this.evaluateExpression(expr.alternate);
- if(!consequent || !alternate) return;
- res = new BasicEvaluatedExpression();
- if(consequent.isConditional())
- res.setOptions(consequent.options);
- else
- res.setOptions([consequent]);
- if(alternate.isConditional())
- res.addOptions(alternate.options);
- else
- res.addOptions([alternate]);
- } else {
- res = this.evaluateExpression(conditionValue ? expr.consequent : expr.alternate);
- }
- res.setRange(expr.range);
- return res;
- });
- this.plugin("evaluate ArrayExpression", function(expr) {
- const items = expr.elements.map(function(element) {
- return element !== null && this.evaluateExpression(element);
- }, this);
- if(!items.every(Boolean)) return;
- return new BasicEvaluatedExpression().setItems(items).setRange(expr.range);
- });
- }
-
- getRenameIdentifier(expr) {
- const result = this.evaluateExpression(expr);
- if(!result) return;
- if(result.isIdentifier()) return result.identifier;
- return;
- }
-
- walkClass(classy) {
- if(classy.superClass)
- this.walkExpression(classy.superClass);
- if(classy.body && classy.body.type === "ClassBody") {
- classy.body.body.forEach(methodDefinition => {
- if(methodDefinition.type === "MethodDefinition")
- this.walkMethodDefinition(methodDefinition);
- });
- }
- }
-
- walkMethodDefinition(methodDefinition) {
- if(methodDefinition.computed && methodDefinition.key)
- this.walkExpression(methodDefinition.key);
- if(methodDefinition.value)
- this.walkExpression(methodDefinition.value);
- }
-
- // Prewalking iterates the scope for variable declarations
- prewalkStatements(statements) {
- for(let index = 0, len = statements.length; index < len; index++) {
- const statement = statements[index];
- this.prewalkStatement(statement);
- }
- }
-
- // Walking iterates the statements and expressions and processes them
- walkStatements(statements) {
- for(let index = 0, len = statements.length; index < len; index++) {
- const statement = statements[index];
- this.walkStatement(statement);
- }
- }
-
- prewalkStatement(statement) {
- const handler = this["prewalk" + statement.type];
- if(handler)
- handler.call(this, statement);
- }
-
- walkStatement(statement) {
- if(this.applyPluginsBailResult1("statement", statement) !== undefined) return;
- const handler = this["walk" + statement.type];
- if(handler)
- handler.call(this, statement);
- }
-
- // Real Statements
- prewalkBlockStatement(statement) {
- this.prewalkStatements(statement.body);
- }
-
- walkBlockStatement(statement) {
- this.walkStatements(statement.body);
- }
-
- walkExpressionStatement(statement) {
- this.walkExpression(statement.expression);
- }
-
- prewalkIfStatement(statement) {
- this.prewalkStatement(statement.consequent);
- if(statement.alternate)
- this.prewalkStatement(statement.alternate);
- }
-
- walkIfStatement(statement) {
- const result = this.applyPluginsBailResult1("statement if", statement);
- if(result === undefined) {
- this.walkExpression(statement.test);
- this.walkStatement(statement.consequent);
- if(statement.alternate)
- this.walkStatement(statement.alternate);
- } else {
- if(result)
- this.walkStatement(statement.consequent);
- else if(statement.alternate)
- this.walkStatement(statement.alternate);
- }
- }
-
- prewalkLabeledStatement(statement) {
- this.prewalkStatement(statement.body);
- }
-
- walkLabeledStatement(statement) {
- const result = this.applyPluginsBailResult1("label " + statement.label.name, statement);
- if(result !== true)
- this.walkStatement(statement.body);
- }
-
- prewalkWithStatement(statement) {
- this.prewalkStatement(statement.body);
- }
-
- walkWithStatement(statement) {
- this.walkExpression(statement.object);
- this.walkStatement(statement.body);
- }
-
- prewalkSwitchStatement(statement) {
- this.prewalkSwitchCases(statement.cases);
- }
-
- walkSwitchStatement(statement) {
- this.walkExpression(statement.discriminant);
- this.walkSwitchCases(statement.cases);
- }
-
- walkTerminatingStatement(statement) {
- if(statement.argument)
- this.walkExpression(statement.argument);
- }
-
- walkReturnStatement(statement) {
- this.walkTerminatingStatement(statement);
- }
-
- walkThrowStatement(statement) {
- this.walkTerminatingStatement(statement);
- }
-
- prewalkTryStatement(statement) {
- this.prewalkStatement(statement.block);
- }
-
- walkTryStatement(statement) {
- if(this.scope.inTry) {
- this.walkStatement(statement.block);
- } else {
- this.scope.inTry = true;
- this.walkStatement(statement.block);
- this.scope.inTry = false;
- }
- if(statement.handler)
- this.walkCatchClause(statement.handler);
- if(statement.finalizer)
- this.walkStatement(statement.finalizer);
- }
-
- prewalkWhileStatement(statement) {
- this.prewalkStatement(statement.body);
- }
-
- walkWhileStatement(statement) {
- this.walkExpression(statement.test);
- this.walkStatement(statement.body);
- }
-
- prewalkDoWhileStatement(statement) {
- this.prewalkStatement(statement.body);
- }
-
- walkDoWhileStatement(statement) {
- this.walkStatement(statement.body);
- this.walkExpression(statement.test);
- }
-
- prewalkForStatement(statement) {
- if(statement.init) {
- if(statement.init.type === "VariableDeclaration")
- this.prewalkStatement(statement.init);
- }
- this.prewalkStatement(statement.body);
- }
-
- walkForStatement(statement) {
- if(statement.init) {
- if(statement.init.type === "VariableDeclaration")
- this.walkStatement(statement.init);
- else
- this.walkExpression(statement.init);
- }
- if(statement.test)
- this.walkExpression(statement.test);
- if(statement.update)
- this.walkExpression(statement.update);
- this.walkStatement(statement.body);
- }
-
- prewalkForInStatement(statement) {
- if(statement.left.type === "VariableDeclaration")
- this.prewalkStatement(statement.left);
- this.prewalkStatement(statement.body);
- }
-
- walkForInStatement(statement) {
- if(statement.left.type === "VariableDeclaration")
- this.walkStatement(statement.left);
- else
- this.walkExpression(statement.left);
- this.walkExpression(statement.right);
- this.walkStatement(statement.body);
- }
-
- prewalkForOfStatement(statement) {
- if(statement.left.type === "VariableDeclaration")
- this.prewalkStatement(statement.left);
- this.prewalkStatement(statement.body);
- }
-
- walkForOfStatement(statement) {
- if(statement.left.type === "VariableDeclaration")
- this.walkStatement(statement.left);
- else
- this.walkExpression(statement.left);
- this.walkExpression(statement.right);
- this.walkStatement(statement.body);
- }
-
- // Declarations
- prewalkFunctionDeclaration(statement) {
- if(statement.id) {
- this.scope.renames["$" + statement.id.name] = undefined;
- this.scope.definitions.push(statement.id.name);
- }
- }
-
- walkFunctionDeclaration(statement) {
- statement.params.forEach(param => {
- this.walkPattern(param);
- });
- this.inScope(statement.params, () => {
- if(statement.body.type === "BlockStatement") {
- this.prewalkStatement(statement.body);
- this.walkStatement(statement.body);
- } else {
- this.walkExpression(statement.body);
- }
- });
- }
-
- prewalkImportDeclaration(statement) {
- const source = statement.source.value;
- this.applyPluginsBailResult("import", statement, source);
- statement.specifiers.forEach(function(specifier) {
- const name = specifier.local.name;
- this.scope.renames["$" + name] = undefined;
- this.scope.definitions.push(name);
- switch(specifier.type) {
- case "ImportDefaultSpecifier":
- this.applyPluginsBailResult("import specifier", statement, source, "default", name);
- break;
- case "ImportSpecifier":
- this.applyPluginsBailResult("import specifier", statement, source, specifier.imported.name, name);
- break;
- case "ImportNamespaceSpecifier":
- this.applyPluginsBailResult("import specifier", statement, source, null, name);
- break;
- }
- }, this);
- }
-
- prewalkExportNamedDeclaration(statement) {
- let source;
- if(statement.source) {
- source = statement.source.value;
- this.applyPluginsBailResult("export import", statement, source);
- } else {
- this.applyPluginsBailResult1("export", statement);
- }
- if(statement.declaration) {
- if(/Expression$/.test(statement.declaration.type)) {
- throw new Error("Doesn't occur?");
- } else {
- if(!this.applyPluginsBailResult("export declaration", statement, statement.declaration)) {
- const pos = this.scope.definitions.length;
- this.prewalkStatement(statement.declaration);
- const newDefs = this.scope.definitions.slice(pos);
- for(let index = newDefs.length - 1; index >= 0; index--) {
- const def = newDefs[index];
- this.applyPluginsBailResult("export specifier", statement, def, def, index);
- }
- }
- }
- }
- if(statement.specifiers) {
- for(let specifierIndex = 0; specifierIndex < statement.specifiers.length; specifierIndex++) {
- const specifier = statement.specifiers[specifierIndex];
- switch(specifier.type) {
- case "ExportSpecifier":
- {
- const name = specifier.exported.name;
- if(source)
- this.applyPluginsBailResult("export import specifier", statement, source, specifier.local.name, name, specifierIndex);
- else
- this.applyPluginsBailResult("export specifier", statement, specifier.local.name, name, specifierIndex);
- break;
- }
- }
- }
- }
- }
-
- walkExportNamedDeclaration(statement) {
- if(statement.declaration) {
- this.walkStatement(statement.declaration);
- }
- }
-
- prewalkExportDefaultDeclaration(statement) {
- if(/Declaration$/.test(statement.declaration.type)) {
- const pos = this.scope.definitions.length;
- this.prewalkStatement(statement.declaration);
- const newDefs = this.scope.definitions.slice(pos);
- for(let index = 0, len = newDefs.length; index < len; index++) {
- const def = newDefs[index];
- this.applyPluginsBailResult("export specifier", statement, def, "default");
- }
- }
- }
-
- walkExportDefaultDeclaration(statement) {
- this.applyPluginsBailResult1("export", statement);
- if(/Declaration$/.test(statement.declaration.type)) {
- if(!this.applyPluginsBailResult("export declaration", statement, statement.declaration)) {
- this.walkStatement(statement.declaration);
- }
- } else {
- this.walkExpression(statement.declaration);
- if(!this.applyPluginsBailResult("export expression", statement, statement.declaration)) {
- this.applyPluginsBailResult("export specifier", statement, statement.declaration, "default");
- }
- }
- }
-
- prewalkExportAllDeclaration(statement) {
- const source = statement.source.value;
- this.applyPluginsBailResult("export import", statement, source);
- this.applyPluginsBailResult("export import specifier", statement, source, null, null, 0);
- }
-
- prewalkVariableDeclaration(statement) {
- if(statement.declarations)
- this.prewalkVariableDeclarators(statement.declarations);
- }
-
- walkVariableDeclaration(statement) {
- if(statement.declarations)
- this.walkVariableDeclarators(statement.declarations);
- }
-
- prewalkClassDeclaration(statement) {
- if(statement.id) {
- this.scope.renames["$" + statement.id.name] = undefined;
- this.scope.definitions.push(statement.id.name);
- }
- }
-
- walkClassDeclaration(statement) {
- this.walkClass(statement);
- }
-
- prewalkSwitchCases(switchCases) {
- for(let index = 0, len = switchCases.length; index < len; index++) {
- const switchCase = switchCases[index];
- this.prewalkStatements(switchCase.consequent);
- }
- }
-
- walkSwitchCases(switchCases) {
- for(let index = 0, len = switchCases.length; index < len; index++) {
- const switchCase = switchCases[index];
-
- if(switchCase.test) {
- this.walkExpression(switchCase.test);
- }
- this.walkStatements(switchCase.consequent);
- }
- }
-
- walkCatchClause(catchClause) {
- this.inScope([catchClause.param], () => {
- this.prewalkStatement(catchClause.body);
- this.walkStatement(catchClause.body);
- });
- }
-
- prewalkVariableDeclarators(declarators) {
- declarators.forEach(declarator => {
- switch(declarator.type) {
- case "VariableDeclarator":
- {
- this.enterPattern(declarator.id, (name, decl) => {
- if(!this.applyPluginsBailResult1("var-" + declarator.kind + " " + name, decl)) {
- if(!this.applyPluginsBailResult1("var " + name, decl)) {
- this.scope.renames["$" + name] = undefined;
- if(this.scope.definitions.indexOf(name) < 0)
- this.scope.definitions.push(name);
- }
- }
- });
- break;
- }
- }
- });
- }
-
- walkVariableDeclarators(declarators) {
- declarators.forEach(declarator => {
- switch(declarator.type) {
- case "VariableDeclarator":
- {
- const renameIdentifier = declarator.init && this.getRenameIdentifier(declarator.init);
- if(renameIdentifier && declarator.id.type === "Identifier" && this.applyPluginsBailResult1("can-rename " + renameIdentifier, declarator.init)) {
- // renaming with "var a = b;"
- if(!this.applyPluginsBailResult1("rename " + renameIdentifier, declarator.init)) {
- this.scope.renames["$" + declarator.id.name] = this.scope.renames["$" + renameIdentifier] || renameIdentifier;
- const idx = this.scope.definitions.indexOf(declarator.id.name);
- if(idx >= 0) this.scope.definitions.splice(idx, 1);
- }
- } else {
- this.walkPattern(declarator.id);
- if(declarator.init)
- this.walkExpression(declarator.init);
- }
- break;
- }
- }
- });
- }
-
- walkPattern(pattern) {
- if(pattern.type === "Identifier")
- return;
- if(this["walk" + pattern.type])
- this["walk" + pattern.type](pattern);
- }
-
- walkAssignmentPattern(pattern) {
- this.walkExpression(pattern.right);
- this.walkPattern(pattern.left);
- }
-
- walkObjectPattern(pattern) {
- for(let i = 0, len = pattern.properties.length; i < len; i++) {
- const prop = pattern.properties[i];
- if(prop) {
- if(prop.computed)
- this.walkExpression(prop.key);
- if(prop.value)
- this.walkPattern(prop.value);
- }
- }
- }
-
- walkArrayPattern(pattern) {
- for(let i = 0, len = pattern.elements.length; i < len; i++) {
- const element = pattern.elements[i];
- if(element)
- this.walkPattern(element);
- }
- }
-
- walkRestElement(pattern) {
- this.walkPattern(pattern.argument);
- }
-
- walkExpressions(expressions) {
- for(let expressionsIndex = 0, len = expressions.length; expressionsIndex < len; expressionsIndex++) {
- const expression = expressions[expressionsIndex];
- if(expression)
- this.walkExpression(expression);
- }
- }
-
- walkExpression(expression) {
- if(this["walk" + expression.type])
- return this["walk" + expression.type](expression);
- }
-
- walkAwaitExpression(expression) {
- const argument = expression.argument;
- if(this["walk" + argument.type])
- return this["walk" + argument.type](argument);
- }
-
- walkArrayExpression(expression) {
- if(expression.elements)
- this.walkExpressions(expression.elements);
- }
-
- walkSpreadElement(expression) {
- if(expression.argument)
- this.walkExpression(expression.argument);
- }
-
- walkObjectExpression(expression) {
- for(let propIndex = 0, len = expression.properties.length; propIndex < len; propIndex++) {
- const prop = expression.properties[propIndex];
- if(prop.computed)
- this.walkExpression(prop.key);
- if(prop.shorthand)
- this.scope.inShorthand = true;
- this.walkExpression(prop.value);
- if(prop.shorthand)
- this.scope.inShorthand = false;
- }
- }
-
- walkFunctionExpression(expression) {
- expression.params.forEach(param => {
- this.walkPattern(param);
- });
- this.inScope(expression.params, () => {
- if(expression.body.type === "BlockStatement") {
- this.prewalkStatement(expression.body);
- this.walkStatement(expression.body);
- } else {
- this.walkExpression(expression.body);
- }
- });
- }
-
- walkArrowFunctionExpression(expression) {
- expression.params.forEach(param => {
- this.walkPattern(param);
- });
- this.inScope(expression.params, () => {
- if(expression.body.type === "BlockStatement") {
- this.prewalkStatement(expression.body);
- this.walkStatement(expression.body);
- } else {
- this.walkExpression(expression.body);
- }
- });
- }
-
- walkSequenceExpression(expression) {
- if(expression.expressions)
- this.walkExpressions(expression.expressions);
- }
-
- walkUpdateExpression(expression) {
- this.walkExpression(expression.argument);
- }
-
- walkUnaryExpression(expression) {
- if(expression.operator === "typeof") {
- const exprName = this.getNameForExpression(expression.argument);
- if(exprName && exprName.free) {
- const result = this.applyPluginsBailResult1("typeof " + exprName.name, expression);
- if(result === true)
- return;
- }
- }
- this.walkExpression(expression.argument);
- }
-
- walkLeftRightExpression(expression) {
- this.walkExpression(expression.left);
- this.walkExpression(expression.right);
- }
-
- walkBinaryExpression(expression) {
- this.walkLeftRightExpression(expression);
- }
-
- walkLogicalExpression(expression) {
- this.walkLeftRightExpression(expression);
- }
-
- walkAssignmentExpression(expression) {
- const renameIdentifier = this.getRenameIdentifier(expression.right);
- if(expression.left.type === "Identifier" && renameIdentifier && this.applyPluginsBailResult1("can-rename " + renameIdentifier, expression.right)) {
- // renaming "a = b;"
- if(!this.applyPluginsBailResult1("rename " + renameIdentifier, expression.right)) {
- this.scope.renames["$" + expression.left.name] = renameIdentifier;
- const idx = this.scope.definitions.indexOf(expression.left.name);
- if(idx >= 0) this.scope.definitions.splice(idx, 1);
- }
- } else if(expression.left.type === "Identifier") {
- if(!this.applyPluginsBailResult1("assigned " + expression.left.name, expression)) {
- this.walkExpression(expression.right);
- }
- this.scope.renames["$" + expression.left.name] = undefined;
- if(!this.applyPluginsBailResult1("assign " + expression.left.name, expression)) {
- this.walkExpression(expression.left);
- }
- } else {
- this.walkExpression(expression.right);
- this.walkPattern(expression.left);
- this.enterPattern(expression.left, (name, decl) => {
- this.scope.renames["$" + name] = undefined;
- });
- }
- }
-
- walkConditionalExpression(expression) {
- const result = this.applyPluginsBailResult1("expression ?:", expression);
- if(result === undefined) {
- this.walkExpression(expression.test);
- this.walkExpression(expression.consequent);
- if(expression.alternate)
- this.walkExpression(expression.alternate);
- } else {
- if(result)
- this.walkExpression(expression.consequent);
- else if(expression.alternate)
- this.walkExpression(expression.alternate);
- }
- }
-
- walkNewExpression(expression) {
- this.walkExpression(expression.callee);
- if(expression.arguments)
- this.walkExpressions(expression.arguments);
- }
-
- walkYieldExpression(expression) {
- if(expression.argument)
- this.walkExpression(expression.argument);
- }
-
- walkTemplateLiteral(expression) {
- if(expression.expressions)
- this.walkExpressions(expression.expressions);
- }
-
- walkTaggedTemplateExpression(expression) {
- if(expression.tag)
- this.walkExpression(expression.tag);
- if(expression.quasi && expression.quasi.expressions)
- this.walkExpressions(expression.quasi.expressions);
- }
-
- walkClassExpression(expression) {
- this.walkClass(expression);
- }
-
- walkCallExpression(expression) {
- let result;
-
- function walkIIFE(functionExpression, options, currentThis) {
- function renameArgOrThis(argOrThis) {
- const renameIdentifier = this.getRenameIdentifier(argOrThis);
- if(renameIdentifier && this.applyPluginsBailResult1("can-rename " + renameIdentifier, argOrThis)) {
- if(!this.applyPluginsBailResult1("rename " + renameIdentifier, argOrThis))
- return renameIdentifier;
- }
- this.walkExpression(argOrThis);
- }
- const params = functionExpression.params;
- const renameThis = currentThis ? renameArgOrThis.call(this, currentThis) : null;
- const args = options.map(renameArgOrThis, this);
- this.inScope(params.filter(function(identifier, idx) {
- return !args[idx];
- }), () => {
- if(renameThis) {
- this.scope.renames.$this = renameThis;
- }
- for(let i = 0; i < args.length; i++) {
- const param = args[i];
- if(!param) continue;
- if(!params[i] || params[i].type !== "Identifier") continue;
- this.scope.renames["$" + params[i].name] = param;
- }
- if(functionExpression.body.type === "BlockStatement") {
- this.prewalkStatement(functionExpression.body);
- this.walkStatement(functionExpression.body);
- } else
- this.walkExpression(functionExpression.body);
- });
- }
- if(expression.callee.type === "MemberExpression" &&
- expression.callee.object.type === "FunctionExpression" &&
- !expression.callee.computed &&
- (["call", "bind"]).indexOf(expression.callee.property.name) >= 0 &&
- expression.arguments &&
- expression.arguments.length > 0
- ) {
- // (function(...) { }.call/bind(?, ...))
- walkIIFE.call(this, expression.callee.object, expression.arguments.slice(1), expression.arguments[0]);
- } else if(expression.callee.type === "FunctionExpression" && expression.arguments) {
- // (function(...) { }(...))
- walkIIFE.call(this, expression.callee, expression.arguments);
- } else if(expression.callee.type === "Import") {
- result = this.applyPluginsBailResult1("import-call", expression);
- if(result === true)
- return;
-
- if(expression.arguments)
- this.walkExpressions(expression.arguments);
- } else {
-
- const callee = this.evaluateExpression(expression.callee);
- if(callee.isIdentifier()) {
- result = this.applyPluginsBailResult1("call " + callee.identifier, expression);
- if(result === true)
- return;
- let identifier = callee.identifier.replace(/\.[^.]+$/, ".*");
- if(identifier !== callee.identifier) {
- result = this.applyPluginsBailResult1("call " + identifier, expression);
- if(result === true)
- return;
- }
- }
-
- if(expression.callee)
- this.walkExpression(expression.callee);
- if(expression.arguments)
- this.walkExpressions(expression.arguments);
- }
- }
-
- walkMemberExpression(expression) {
- const exprName = this.getNameForExpression(expression);
- if(exprName && exprName.free) {
- let result = this.applyPluginsBailResult1("expression " + exprName.name, expression);
- if(result === true)
- return;
- result = this.applyPluginsBailResult1("expression " + exprName.nameGeneral, expression);
- if(result === true)
- return;
- }
- this.walkExpression(expression.object);
- if(expression.computed === true)
- this.walkExpression(expression.property);
- }
-
- walkIdentifier(expression) {
- if(this.scope.definitions.indexOf(expression.name) === -1) {
- const result = this.applyPluginsBailResult1("expression " + (this.scope.renames["$" + expression.name] || expression.name), expression);
- if(result === true)
- return;
- }
- }
-
- inScope(params, fn) {
- const oldScope = this.scope;
- this.scope = {
- inTry: false,
- inShorthand: false,
- definitions: oldScope.definitions.slice(),
- renames: Object.create(oldScope.renames)
- };
-
- this.scope.renames.$this = undefined;
-
- for(let paramIndex = 0, len = params.length; paramIndex < len; paramIndex++) {
- const param = params[paramIndex];
-
- if(typeof param !== "string") {
- this.enterPattern(param, param => {
- this.scope.renames["$" + param] = undefined;
- this.scope.definitions.push(param);
- });
- } else {
- this.scope.renames["$" + param] = undefined;
- this.scope.definitions.push(param);
- }
- }
-
- fn();
- this.scope = oldScope;
- }
-
- enterPattern(pattern, onIdent) {
- if(pattern && this["enter" + pattern.type])
- this["enter" + pattern.type](pattern, onIdent);
- }
-
- enterIdentifier(pattern, onIdent) {
- onIdent(pattern.name, pattern);
- }
-
- enterObjectPattern(pattern, onIdent) {
- for(let propIndex = 0, len = pattern.properties.length; propIndex < len; propIndex++) {
- const prop = pattern.properties[propIndex];
- this.enterPattern(prop.value, onIdent);
- }
- }
-
- enterArrayPattern(pattern, onIdent) {
- for(let elementIndex = 0, len = pattern.elements.length; elementIndex < len; elementIndex++) {
- const element = pattern.elements[elementIndex];
- this.enterPattern(element, onIdent);
- }
- }
-
- enterRestElement(pattern, onIdent) {
- this.enterPattern(pattern.argument, onIdent);
- }
-
- enterAssignmentPattern(pattern, onIdent) {
- this.enterPattern(pattern.left, onIdent);
- }
-
- evaluateExpression(expression) {
- try {
- const result = this.applyPluginsBailResult1("evaluate " + expression.type, expression);
- if(result !== undefined)
- return result;
- } catch(e) {
- console.warn(e);
- // ignore error
- }
- return new BasicEvaluatedExpression().setRange(expression.range);
- }
-
- parseString(expression) {
- switch(expression.type) {
- case "BinaryExpression":
- if(expression.operator === "+")
- return this.parseString(expression.left) + this.parseString(expression.right);
- break;
- case "Literal":
- return expression.value + "";
- }
- throw new Error(expression.type + " is not supported as parameter for require");
- }
-
- parseCalculatedString(expression) {
- switch(expression.type) {
- case "BinaryExpression":
- if(expression.operator === "+") {
- const left = this.parseCalculatedString(expression.left);
- const right = this.parseCalculatedString(expression.right);
- if(left.code) {
- return {
- range: left.range,
- value: left.value,
- code: true
- };
- } else if(right.code) {
- return {
- range: [left.range[0], right.range ? right.range[1] : left.range[1]],
- value: left.value + right.value,
- code: true
- };
- } else {
- return {
- range: [left.range[0], right.range[1]],
- value: left.value + right.value
- };
- }
- }
- break;
- case "ConditionalExpression":
- {
- const consequent = this.parseCalculatedString(expression.consequent);
- const alternate = this.parseCalculatedString(expression.alternate);
- const items = [];
- if(consequent.conditional)
- Array.prototype.push.apply(items, consequent.conditional);
- else if(!consequent.code)
- items.push(consequent);
- else break;
- if(alternate.conditional)
- Array.prototype.push.apply(items, alternate.conditional);
- else if(!alternate.code)
- items.push(alternate);
- else break;
- return {
- value: "",
- code: true,
- conditional: items
- };
- }
- case "Literal":
- return {
- range: expression.range,
- value: expression.value + ""
- };
- }
- return {
- value: "",
- code: true
- };
- }
-
- parseStringArray(expression) {
- if(expression.type !== "ArrayExpression") {
- return [this.parseString(expression)];
- }
-
- const arr = [];
- if(expression.elements)
- expression.elements.forEach(function(expr) {
- arr.push(this.parseString(expr));
- }, this);
- return arr;
- }
-
- parseCalculatedStringArray(expression) {
- if(expression.type !== "ArrayExpression") {
- return [this.parseCalculatedString(expression)];
- }
-
- const arr = [];
- if(expression.elements)
- expression.elements.forEach(function(expr) {
- arr.push(this.parseCalculatedString(expr));
- }, this);
- return arr;
- }
-
- parse(source, initialState) {
- let ast;
- const comments = [];
- for(let i = 0, len = POSSIBLE_AST_OPTIONS.length; i < len; i++) {
- if(!ast) {
- try {
- comments.length = 0;
- POSSIBLE_AST_OPTIONS[i].onComment = comments;
- ast = acorn.parse(source, POSSIBLE_AST_OPTIONS[i]);
- } catch(e) {
- // ignore the error
- }
- }
- }
- if(!ast) {
- // for the error
- ast = acorn.parse(source, {
- ranges: true,
- locations: true,
- ecmaVersion: ECMA_VERSION,
- sourceType: "module",
- plugins: {
- dynamicImport: true
- },
- onComment: comments
- });
- }
- if(!ast || typeof ast !== "object")
- throw new Error("Source couldn't be parsed");
- const oldScope = this.scope;
- const oldState = this.state;
- const oldComments = this.comments;
- this.scope = {
- inTry: false,
- definitions: [],
- renames: {}
- };
- const state = this.state = initialState || {};
- this.comments = comments;
- if(this.applyPluginsBailResult("program", ast, comments) === undefined) {
- this.prewalkStatements(ast.body);
- this.walkStatements(ast.body);
- }
- this.scope = oldScope;
- this.state = oldState;
- this.comments = oldComments;
- return state;
- }
-
- evaluate(source) {
- const ast = acorn.parse("(" + source + ")", {
- ranges: true,
- locations: true,
- ecmaVersion: ECMA_VERSION,
- sourceType: "module",
- plugins: {
- dynamicImport: true
- }
- });
- if(!ast || typeof ast !== "object" || ast.type !== "Program")
- throw new Error("evaluate: Source couldn't be parsed");
- if(ast.body.length !== 1 || ast.body[0].type !== "ExpressionStatement")
- throw new Error("evaluate: Source is not a expression");
- return this.evaluateExpression(ast.body[0].expression);
- }
-
- getComments(range) {
- return this.comments.filter(comment => comment.range[0] >= range[0] && comment.range[1] <= range[1]);
- }
-
- getCommentOptions(range) {
- const comments = this.getComments(range);
- if(comments.length === 0) return null;
- const options = comments.map(comment => {
- try {
- return json5.parse(`{${comment.value}}`);
- } catch(e) {
- return {};
- }
- });
- return options.reduce((o, i) => Object.assign(o, i), {});
- }
-
- getNameForExpression(expression) {
- let expr = expression;
- const exprName = [];
- while(expr.type === "MemberExpression" && expr.property.type === (expr.computed ? "Literal" : "Identifier")) {
- exprName.push(expr.computed ? expr.property.value : expr.property.name);
- expr = expr.object;
- }
- let free;
- if(expr.type === "Identifier") {
- free = this.scope.definitions.indexOf(expr.name) === -1;
- exprName.push(this.scope.renames["$" + expr.name] || expr.name);
- } else if(expr.type === "ThisExpression" && this.scope.renames.$this) {
- free = true;
- exprName.push(this.scope.renames.$this);
- } else if(expr.type === "ThisExpression") {
- free = false;
- exprName.push("this");
- } else {
- return null;
- }
- let prefix = "";
- for(let i = exprName.length - 1; i >= 1; i--)
- prefix += exprName[i] + ".";
- const name = prefix + exprName[0];
- const nameGeneral = prefix + "*";
- return {
- name,
- nameGeneral,
- free
- };
- }
-
-}
-
-Parser.ECMA_VERSION = ECMA_VERSION;
-
-module.exports = Parser;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +// Syntax: https://developer.mozilla.org/en/SpiderMonkey/Parser_API + +const acorn = require("acorn-dynamic-import").default; +const { Tapable, SyncBailHook, HookMap } = require("tapable"); +const util = require("util"); +const vm = require("vm"); +const BasicEvaluatedExpression = require("./BasicEvaluatedExpression"); +const StackedSetMap = require("./util/StackedSetMap"); +const TrackingSet = require("./util/TrackingSet"); + +const joinRanges = (startRange, endRange) => { + if (!endRange) return startRange; + if (!startRange) return endRange; + return [startRange[0], endRange[1]]; +}; + +const defaultParserOptions = { + ranges: true, + locations: true, + ecmaVersion: 2019, + sourceType: "module", + onComment: null, + plugins: { + dynamicImport: true + } +}; + +// regexp to match at lease one "magic comment" +const webpackCommentRegExp = new RegExp(/(^|\W)webpack[A-Z]{1,}[A-Za-z]{1,}:/); + +const EMPTY_ARRAY = []; + +const EMPTY_COMMENT_OPTIONS = { + options: null, + errors: null +}; + +class Parser extends Tapable { + constructor(options, sourceType = "auto") { + super(); + this.hooks = { + evaluateTypeof: new HookMap(() => new SyncBailHook(["expression"])), + evaluate: new HookMap(() => new SyncBailHook(["expression"])), + evaluateIdentifier: new HookMap(() => new SyncBailHook(["expression"])), + evaluateDefinedIdentifier: new HookMap( + () => new SyncBailHook(["expression"]) + ), + evaluateCallExpressionMember: new HookMap( + () => new SyncBailHook(["expression", "param"]) + ), + statement: new SyncBailHook(["statement"]), + statementIf: new SyncBailHook(["statement"]), + label: new HookMap(() => new SyncBailHook(["statement"])), + import: new SyncBailHook(["statement", "source"]), + importSpecifier: new SyncBailHook([ + "statement", + "source", + "exportName", + "identifierName" + ]), + export: new SyncBailHook(["statement"]), + exportImport: new SyncBailHook(["statement", "source"]), + exportDeclaration: new SyncBailHook(["statement", "declaration"]), + exportExpression: new SyncBailHook(["statement", "declaration"]), + exportSpecifier: new SyncBailHook([ + "statement", + "identifierName", + "exportName", + "index" + ]), + exportImportSpecifier: new SyncBailHook([ + "statement", + "source", + "identifierName", + "exportName", + "index" + ]), + varDeclaration: new HookMap(() => new SyncBailHook(["declaration"])), + varDeclarationLet: new HookMap(() => new SyncBailHook(["declaration"])), + varDeclarationConst: new HookMap(() => new SyncBailHook(["declaration"])), + varDeclarationVar: new HookMap(() => new SyncBailHook(["declaration"])), + canRename: new HookMap(() => new SyncBailHook(["initExpression"])), + rename: new HookMap(() => new SyncBailHook(["initExpression"])), + assigned: new HookMap(() => new SyncBailHook(["expression"])), + assign: new HookMap(() => new SyncBailHook(["expression"])), + typeof: new HookMap(() => new SyncBailHook(["expression"])), + importCall: new SyncBailHook(["expression"]), + call: new HookMap(() => new SyncBailHook(["expression"])), + callAnyMember: new HookMap(() => new SyncBailHook(["expression"])), + new: new HookMap(() => new SyncBailHook(["expression"])), + expression: new HookMap(() => new SyncBailHook(["expression"])), + expressionAnyMember: new HookMap(() => new SyncBailHook(["expression"])), + expressionConditionalOperator: new SyncBailHook(["expression"]), + program: new SyncBailHook(["ast", "comments"]) + }; + const HOOK_MAP_COMPAT_CONFIG = { + evaluateTypeof: /^evaluate typeof (.+)$/, + evaluateIdentifier: /^evaluate Identifier (.+)$/, + evaluateDefinedIdentifier: /^evaluate defined Identifier (.+)$/, + evaluateCallExpressionMember: /^evaluate CallExpression .(.+)$/, + evaluate: /^evaluate (.+)$/, + label: /^label (.+)$/, + varDeclarationLet: /^var-let (.+)$/, + varDeclarationConst: /^var-const (.+)$/, + varDeclarationVar: /^var-var (.+)$/, + varDeclaration: /^var (.+)$/, + canRename: /^can-rename (.+)$/, + rename: /^rename (.+)$/, + typeof: /^typeof (.+)$/, + assigned: /^assigned (.+)$/, + assign: /^assign (.+)$/, + callAnyMember: /^call (.+)\.\*$/, + call: /^call (.+)$/, + new: /^new (.+)$/, + expressionConditionalOperator: /^expression \?:$/, + expressionAnyMember: /^expression (.+)\.\*$/, + expression: /^expression (.+)$/ + }; + this._pluginCompat.tap("Parser", options => { + for (const name of Object.keys(HOOK_MAP_COMPAT_CONFIG)) { + const regexp = HOOK_MAP_COMPAT_CONFIG[name]; + const match = regexp.exec(options.name); + if (match) { + if (match[1]) { + this.hooks[name].tap( + match[1], + options.fn.name || "unnamed compat plugin", + options.fn.bind(this) + ); + } else { + this.hooks[name].tap( + options.fn.name || "unnamed compat plugin", + options.fn.bind(this) + ); + } + return true; + } + } + }); + this.options = options; + this.sourceType = sourceType; + this.scope = undefined; + this.state = undefined; + this.comments = undefined; + this.initializeEvaluating(); + } + + initializeEvaluating() { + this.hooks.evaluate.for("Literal").tap("Parser", expr => { + switch (typeof expr.value) { + case "number": + return new BasicEvaluatedExpression() + .setNumber(expr.value) + .setRange(expr.range); + case "string": + return new BasicEvaluatedExpression() + .setString(expr.value) + .setRange(expr.range); + case "boolean": + return new BasicEvaluatedExpression() + .setBoolean(expr.value) + .setRange(expr.range); + } + if (expr.value === null) { + return new BasicEvaluatedExpression().setNull().setRange(expr.range); + } + if (expr.value instanceof RegExp) { + return new BasicEvaluatedExpression() + .setRegExp(expr.value) + .setRange(expr.range); + } + }); + this.hooks.evaluate.for("LogicalExpression").tap("Parser", expr => { + let left; + let leftAsBool; + let right; + if (expr.operator === "&&") { + left = this.evaluateExpression(expr.left); + leftAsBool = left && left.asBool(); + if (leftAsBool === false) return left.setRange(expr.range); + if (leftAsBool !== true) return; + right = this.evaluateExpression(expr.right); + return right.setRange(expr.range); + } else if (expr.operator === "||") { + left = this.evaluateExpression(expr.left); + leftAsBool = left && left.asBool(); + if (leftAsBool === true) return left.setRange(expr.range); + if (leftAsBool !== false) return; + right = this.evaluateExpression(expr.right); + return right.setRange(expr.range); + } + }); + this.hooks.evaluate.for("BinaryExpression").tap("Parser", expr => { + let left; + let right; + let res; + if (expr.operator === "+") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + res = new BasicEvaluatedExpression(); + if (left.isString()) { + if (right.isString()) { + res.setString(left.string + right.string); + } else if (right.isNumber()) { + res.setString(left.string + right.number); + } else if ( + right.isWrapped() && + right.prefix && + right.prefix.isString() + ) { + res.setWrapped( + new BasicEvaluatedExpression() + .setString(left.string + right.prefix.string) + .setRange(joinRanges(left.range, right.prefix.range)), + right.postfix + ); + } else if (right.isWrapped()) { + res.setWrapped( + new BasicEvaluatedExpression() + .setString(left.string) + .setRange(left.range), + right.postfix + ); + } else { + res.setWrapped(left, null); + } + } else if (left.isNumber()) { + if (right.isString()) { + res.setString(left.number + right.string); + } else if (right.isNumber()) { + res.setNumber(left.number + right.number); + } + } else if (left.isWrapped()) { + if (left.postfix && left.postfix.isString() && right.isString()) { + res.setWrapped( + left.prefix, + new BasicEvaluatedExpression() + .setString(left.postfix.string + right.string) + .setRange(joinRanges(left.postfix.range, right.range)) + ); + } else if ( + left.postfix && + left.postfix.isString() && + right.isNumber() + ) { + res.setWrapped( + left.prefix, + new BasicEvaluatedExpression() + .setString(left.postfix.string + right.number) + .setRange(joinRanges(left.postfix.range, right.range)) + ); + } else if (right.isString()) { + res.setWrapped(left.prefix, right); + } else if (right.isNumber()) { + res.setWrapped( + left.prefix, + new BasicEvaluatedExpression() + .setString(right.number + "") + .setRange(right.range) + ); + } else { + res.setWrapped(left.prefix, new BasicEvaluatedExpression()); + } + } else { + if (right.isString()) { + res.setWrapped(null, right); + } + } + res.setRange(expr.range); + return res; + } else if (expr.operator === "-") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + if (!left.isNumber() || !right.isNumber()) return; + res = new BasicEvaluatedExpression(); + res.setNumber(left.number - right.number); + res.setRange(expr.range); + return res; + } else if (expr.operator === "*") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + if (!left.isNumber() || !right.isNumber()) return; + res = new BasicEvaluatedExpression(); + res.setNumber(left.number * right.number); + res.setRange(expr.range); + return res; + } else if (expr.operator === "/") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + if (!left.isNumber() || !right.isNumber()) return; + res = new BasicEvaluatedExpression(); + res.setNumber(left.number / right.number); + res.setRange(expr.range); + return res; + } else if (expr.operator === "**") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + if (!left.isNumber() || !right.isNumber()) return; + res = new BasicEvaluatedExpression(); + res.setNumber(Math.pow(left.number, right.number)); + res.setRange(expr.range); + return res; + } else if (expr.operator === "==" || expr.operator === "===") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + res = new BasicEvaluatedExpression(); + res.setRange(expr.range); + if (left.isString() && right.isString()) { + return res.setBoolean(left.string === right.string); + } else if (left.isNumber() && right.isNumber()) { + return res.setBoolean(left.number === right.number); + } else if (left.isBoolean() && right.isBoolean()) { + return res.setBoolean(left.bool === right.bool); + } + } else if (expr.operator === "!=" || expr.operator === "!==") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + res = new BasicEvaluatedExpression(); + res.setRange(expr.range); + if (left.isString() && right.isString()) { + return res.setBoolean(left.string !== right.string); + } else if (left.isNumber() && right.isNumber()) { + return res.setBoolean(left.number !== right.number); + } else if (left.isBoolean() && right.isBoolean()) { + return res.setBoolean(left.bool !== right.bool); + } + } else if (expr.operator === "&") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + if (!left.isNumber() || !right.isNumber()) return; + res = new BasicEvaluatedExpression(); + res.setNumber(left.number & right.number); + res.setRange(expr.range); + return res; + } else if (expr.operator === "|") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + if (!left.isNumber() || !right.isNumber()) return; + res = new BasicEvaluatedExpression(); + res.setNumber(left.number | right.number); + res.setRange(expr.range); + return res; + } else if (expr.operator === "^") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + if (!left.isNumber() || !right.isNumber()) return; + res = new BasicEvaluatedExpression(); + res.setNumber(left.number ^ right.number); + res.setRange(expr.range); + return res; + } else if (expr.operator === ">>>") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + if (!left.isNumber() || !right.isNumber()) return; + res = new BasicEvaluatedExpression(); + res.setNumber(left.number >>> right.number); + res.setRange(expr.range); + return res; + } else if (expr.operator === ">>") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + if (!left.isNumber() || !right.isNumber()) return; + res = new BasicEvaluatedExpression(); + res.setNumber(left.number >> right.number); + res.setRange(expr.range); + return res; + } else if (expr.operator === "<<") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + if (!left.isNumber() || !right.isNumber()) return; + res = new BasicEvaluatedExpression(); + res.setNumber(left.number << right.number); + res.setRange(expr.range); + return res; + } + }); + this.hooks.evaluate.for("UnaryExpression").tap("Parser", expr => { + if (expr.operator === "typeof") { + let res; + let name; + if (expr.argument.type === "Identifier") { + name = + this.scope.renames.get(expr.argument.name) || expr.argument.name; + if (!this.scope.definitions.has(name)) { + const hook = this.hooks.evaluateTypeof.get(name); + if (hook !== undefined) { + res = hook.call(expr); + if (res !== undefined) return res; + } + } + } + if (expr.argument.type === "MemberExpression") { + const exprName = this.getNameForExpression(expr.argument); + if (exprName && exprName.free) { + const hook = this.hooks.evaluateTypeof.get(exprName.name); + if (hook !== undefined) { + res = hook.call(expr); + if (res !== undefined) return res; + } + } + } + if (expr.argument.type === "FunctionExpression") { + return new BasicEvaluatedExpression() + .setString("function") + .setRange(expr.range); + } + const arg = this.evaluateExpression(expr.argument); + if (arg.isString() || arg.isWrapped()) { + return new BasicEvaluatedExpression() + .setString("string") + .setRange(expr.range); + } + if (arg.isNumber()) { + return new BasicEvaluatedExpression() + .setString("number") + .setRange(expr.range); + } + if (arg.isBoolean()) { + return new BasicEvaluatedExpression() + .setString("boolean") + .setRange(expr.range); + } + if (arg.isArray() || arg.isConstArray() || arg.isRegExp()) { + return new BasicEvaluatedExpression() + .setString("object") + .setRange(expr.range); + } + } else if (expr.operator === "!") { + const argument = this.evaluateExpression(expr.argument); + if (!argument) return; + if (argument.isBoolean()) { + return new BasicEvaluatedExpression() + .setBoolean(!argument.bool) + .setRange(expr.range); + } + if (argument.isTruthy()) { + return new BasicEvaluatedExpression() + .setBoolean(false) + .setRange(expr.range); + } + if (argument.isFalsy()) { + return new BasicEvaluatedExpression() + .setBoolean(true) + .setRange(expr.range); + } + if (argument.isString()) { + return new BasicEvaluatedExpression() + .setBoolean(!argument.string) + .setRange(expr.range); + } + if (argument.isNumber()) { + return new BasicEvaluatedExpression() + .setBoolean(!argument.number) + .setRange(expr.range); + } + } else if (expr.operator === "~") { + const argument = this.evaluateExpression(expr.argument); + if (!argument) return; + if (!argument.isNumber()) return; + const res = new BasicEvaluatedExpression(); + res.setNumber(~argument.number); + res.setRange(expr.range); + return res; + } + }); + this.hooks.evaluateTypeof.for("undefined").tap("Parser", expr => { + return new BasicEvaluatedExpression() + .setString("undefined") + .setRange(expr.range); + }); + this.hooks.evaluate.for("Identifier").tap("Parser", expr => { + const name = this.scope.renames.get(expr.name) || expr.name; + if (!this.scope.definitions.has(expr.name)) { + const hook = this.hooks.evaluateIdentifier.get(name); + if (hook !== undefined) { + const result = hook.call(expr); + if (result) return result; + } + return new BasicEvaluatedExpression() + .setIdentifier(name) + .setRange(expr.range); + } else { + const hook = this.hooks.evaluateDefinedIdentifier.get(name); + if (hook !== undefined) { + return hook.call(expr); + } + } + }); + this.hooks.evaluate.for("ThisExpression").tap("Parser", expr => { + const name = this.scope.renames.get("this"); + if (name) { + const hook = this.hooks.evaluateIdentifier.get(name); + if (hook !== undefined) { + const result = hook.call(expr); + if (result) return result; + } + return new BasicEvaluatedExpression() + .setIdentifier(name) + .setRange(expr.range); + } + }); + this.hooks.evaluate.for("MemberExpression").tap("Parser", expression => { + let exprName = this.getNameForExpression(expression); + if (exprName) { + if (exprName.free) { + const hook = this.hooks.evaluateIdentifier.get(exprName.name); + if (hook !== undefined) { + const result = hook.call(expression); + if (result) return result; + } + return new BasicEvaluatedExpression() + .setIdentifier(exprName.name) + .setRange(expression.range); + } else { + const hook = this.hooks.evaluateDefinedIdentifier.get(exprName.name); + if (hook !== undefined) { + return hook.call(expression); + } + } + } + }); + this.hooks.evaluate.for("CallExpression").tap("Parser", expr => { + if (expr.callee.type !== "MemberExpression") return; + if ( + expr.callee.property.type !== + (expr.callee.computed ? "Literal" : "Identifier") + ) + return; + const param = this.evaluateExpression(expr.callee.object); + if (!param) return; + const property = expr.callee.property.name || expr.callee.property.value; + const hook = this.hooks.evaluateCallExpressionMember.get(property); + if (hook !== undefined) { + return hook.call(expr, param); + } + }); + this.hooks.evaluateCallExpressionMember + .for("replace") + .tap("Parser", (expr, param) => { + if (!param.isString()) return; + if (expr.arguments.length !== 2) return; + let arg1 = this.evaluateExpression(expr.arguments[0]); + let arg2 = this.evaluateExpression(expr.arguments[1]); + if (!arg1.isString() && !arg1.isRegExp()) return; + arg1 = arg1.regExp || arg1.string; + if (!arg2.isString()) return; + arg2 = arg2.string; + return new BasicEvaluatedExpression() + .setString(param.string.replace(arg1, arg2)) + .setRange(expr.range); + }); + ["substr", "substring"].forEach(fn => { + this.hooks.evaluateCallExpressionMember + .for(fn) + .tap("Parser", (expr, param) => { + if (!param.isString()) return; + let arg1; + let result, + str = param.string; + switch (expr.arguments.length) { + case 1: + arg1 = this.evaluateExpression(expr.arguments[0]); + if (!arg1.isNumber()) return; + result = str[fn](arg1.number); + break; + case 2: { + arg1 = this.evaluateExpression(expr.arguments[0]); + const arg2 = this.evaluateExpression(expr.arguments[1]); + if (!arg1.isNumber()) return; + if (!arg2.isNumber()) return; + result = str[fn](arg1.number, arg2.number); + break; + } + default: + return; + } + return new BasicEvaluatedExpression() + .setString(result) + .setRange(expr.range); + }); + }); + + /** + * @param {string} kind "cooked" | "raw" + * @param {TODO[]} quasis quasis + * @param {TODO[]} expressions expressions + * @returns {BasicEvaluatedExpression[]} Simplified template + */ + const getSimplifiedTemplateResult = (kind, quasis, expressions) => { + const parts = []; + + for (let i = 0; i < quasis.length; i++) { + parts.push( + new BasicEvaluatedExpression() + .setString(quasis[i].value[kind]) + .setRange(quasis[i].range) + ); + + if (i > 0) { + const prevExpr = parts[parts.length - 2], + lastExpr = parts[parts.length - 1]; + const expr = this.evaluateExpression(expressions[i - 1]); + if (!(expr.isString() || expr.isNumber())) continue; + + prevExpr.setString( + prevExpr.string + + (expr.isString() ? expr.string : expr.number) + + lastExpr.string + ); + prevExpr.setRange([prevExpr.range[0], lastExpr.range[1]]); + parts.pop(); + } + } + return parts; + }; + + this.hooks.evaluate.for("TemplateLiteral").tap("Parser", node => { + const parts = getSimplifiedTemplateResult.call( + this, + "cooked", + node.quasis, + node.expressions + ); + if (parts.length === 1) { + return parts[0].setRange(node.range); + } + return new BasicEvaluatedExpression() + .setTemplateString(parts) + .setRange(node.range); + }); + this.hooks.evaluate.for("TaggedTemplateExpression").tap("Parser", node => { + if (this.evaluateExpression(node.tag).identifier !== "String.raw") return; + const parts = getSimplifiedTemplateResult.call( + this, + "raw", + node.quasi.quasis, + node.quasi.expressions + ); + return new BasicEvaluatedExpression() + .setTemplateString(parts) + .setRange(node.range); + }); + + this.hooks.evaluateCallExpressionMember + .for("concat") + .tap("Parser", (expr, param) => { + if (!param.isString() && !param.isWrapped()) return; + + let stringSuffix = null; + let hasUnknownParams = false; + for (let i = expr.arguments.length - 1; i >= 0; i--) { + const argExpr = this.evaluateExpression(expr.arguments[i]); + if (!argExpr.isString() && !argExpr.isNumber()) { + hasUnknownParams = true; + break; + } + + const value = argExpr.isString() + ? argExpr.string + : "" + argExpr.number; + + const newString = value + (stringSuffix ? stringSuffix.string : ""); + const newRange = [ + argExpr.range[0], + (stringSuffix || argExpr).range[1] + ]; + stringSuffix = new BasicEvaluatedExpression() + .setString(newString) + .setRange(newRange); + } + + if (hasUnknownParams) { + const prefix = param.isString() ? param : param.prefix; + return new BasicEvaluatedExpression() + .setWrapped(prefix, stringSuffix) + .setRange(expr.range); + } else if (param.isWrapped()) { + const postfix = stringSuffix || param.postfix; + return new BasicEvaluatedExpression() + .setWrapped(param.prefix, postfix) + .setRange(expr.range); + } else { + const newString = + param.string + (stringSuffix ? stringSuffix.string : ""); + return new BasicEvaluatedExpression() + .setString(newString) + .setRange(expr.range); + } + }); + this.hooks.evaluateCallExpressionMember + .for("split") + .tap("Parser", (expr, param) => { + if (!param.isString()) return; + if (expr.arguments.length !== 1) return; + let result; + const arg = this.evaluateExpression(expr.arguments[0]); + if (arg.isString()) { + result = param.string.split(arg.string); + } else if (arg.isRegExp()) { + result = param.string.split(arg.regExp); + } else { + return; + } + return new BasicEvaluatedExpression() + .setArray(result) + .setRange(expr.range); + }); + this.hooks.evaluate.for("ConditionalExpression").tap("Parser", expr => { + const condition = this.evaluateExpression(expr.test); + const conditionValue = condition.asBool(); + let res; + if (conditionValue === undefined) { + const consequent = this.evaluateExpression(expr.consequent); + const alternate = this.evaluateExpression(expr.alternate); + if (!consequent || !alternate) return; + res = new BasicEvaluatedExpression(); + if (consequent.isConditional()) { + res.setOptions(consequent.options); + } else { + res.setOptions([consequent]); + } + if (alternate.isConditional()) { + res.addOptions(alternate.options); + } else { + res.addOptions([alternate]); + } + } else { + res = this.evaluateExpression( + conditionValue ? expr.consequent : expr.alternate + ); + } + res.setRange(expr.range); + return res; + }); + this.hooks.evaluate.for("ArrayExpression").tap("Parser", expr => { + const items = expr.elements.map(element => { + return element !== null && this.evaluateExpression(element); + }); + if (!items.every(Boolean)) return; + return new BasicEvaluatedExpression() + .setItems(items) + .setRange(expr.range); + }); + } + + getRenameIdentifier(expr) { + const result = this.evaluateExpression(expr); + if (result && result.isIdentifier()) { + return result.identifier; + } + } + + walkClass(classy) { + if (classy.superClass) this.walkExpression(classy.superClass); + if (classy.body && classy.body.type === "ClassBody") { + const wasTopLevel = this.scope.topLevelScope; + this.scope.topLevelScope = false; + for (const methodDefinition of classy.body.body) { + if (methodDefinition.type === "MethodDefinition") { + this.walkMethodDefinition(methodDefinition); + } + } + this.scope.topLevelScope = wasTopLevel; + } + } + + walkMethodDefinition(methodDefinition) { + if (methodDefinition.computed && methodDefinition.key) { + this.walkExpression(methodDefinition.key); + } + if (methodDefinition.value) { + this.walkExpression(methodDefinition.value); + } + } + + // Prewalking iterates the scope for variable declarations + prewalkStatements(statements) { + for (let index = 0, len = statements.length; index < len; index++) { + const statement = statements[index]; + this.prewalkStatement(statement); + } + } + + // Walking iterates the statements and expressions and processes them + walkStatements(statements) { + for (let index = 0, len = statements.length; index < len; index++) { + const statement = statements[index]; + this.walkStatement(statement); + } + } + + prewalkStatement(statement) { + switch (statement.type) { + case "BlockStatement": + this.prewalkBlockStatement(statement); + break; + case "ClassDeclaration": + this.prewalkClassDeclaration(statement); + break; + case "DoWhileStatement": + this.prewalkDoWhileStatement(statement); + break; + case "ExportAllDeclaration": + this.prewalkExportAllDeclaration(statement); + break; + case "ExportDefaultDeclaration": + this.prewalkExportDefaultDeclaration(statement); + break; + case "ExportNamedDeclaration": + this.prewalkExportNamedDeclaration(statement); + break; + case "ForInStatement": + this.prewalkForInStatement(statement); + break; + case "ForOfStatement": + this.prewalkForOfStatement(statement); + break; + case "ForStatement": + this.prewalkForStatement(statement); + break; + case "FunctionDeclaration": + this.prewalkFunctionDeclaration(statement); + break; + case "IfStatement": + this.prewalkIfStatement(statement); + break; + case "ImportDeclaration": + this.prewalkImportDeclaration(statement); + break; + case "LabeledStatement": + this.prewalkLabeledStatement(statement); + break; + case "SwitchStatement": + this.prewalkSwitchStatement(statement); + break; + case "TryStatement": + this.prewalkTryStatement(statement); + break; + case "VariableDeclaration": + this.prewalkVariableDeclaration(statement); + break; + case "WhileStatement": + this.prewalkWhileStatement(statement); + break; + case "WithStatement": + this.prewalkWithStatement(statement); + break; + } + } + + walkStatement(statement) { + if (this.hooks.statement.call(statement) !== undefined) return; + switch (statement.type) { + case "BlockStatement": + this.walkBlockStatement(statement); + break; + case "ClassDeclaration": + this.walkClassDeclaration(statement); + break; + case "DoWhileStatement": + this.walkDoWhileStatement(statement); + break; + case "ExportDefaultDeclaration": + this.walkExportDefaultDeclaration(statement); + break; + case "ExportNamedDeclaration": + this.walkExportNamedDeclaration(statement); + break; + case "ExpressionStatement": + this.walkExpressionStatement(statement); + break; + case "ForInStatement": + this.walkForInStatement(statement); + break; + case "ForOfStatement": + this.walkForOfStatement(statement); + break; + case "ForStatement": + this.walkForStatement(statement); + break; + case "FunctionDeclaration": + this.walkFunctionDeclaration(statement); + break; + case "IfStatement": + this.walkIfStatement(statement); + break; + case "LabeledStatement": + this.walkLabeledStatement(statement); + break; + case "ReturnStatement": + this.walkReturnStatement(statement); + break; + case "SwitchStatement": + this.walkSwitchStatement(statement); + break; + case "ThrowStatement": + this.walkThrowStatement(statement); + break; + case "TryStatement": + this.walkTryStatement(statement); + break; + case "VariableDeclaration": + this.walkVariableDeclaration(statement); + break; + case "WhileStatement": + this.walkWhileStatement(statement); + break; + case "WithStatement": + this.walkWithStatement(statement); + break; + } + } + + // Real Statements + prewalkBlockStatement(statement) { + this.prewalkStatements(statement.body); + } + + walkBlockStatement(statement) { + this.walkStatements(statement.body); + } + + walkExpressionStatement(statement) { + this.walkExpression(statement.expression); + } + + prewalkIfStatement(statement) { + this.prewalkStatement(statement.consequent); + if (statement.alternate) { + this.prewalkStatement(statement.alternate); + } + } + + walkIfStatement(statement) { + const result = this.hooks.statementIf.call(statement); + if (result === undefined) { + this.walkExpression(statement.test); + this.walkStatement(statement.consequent); + if (statement.alternate) { + this.walkStatement(statement.alternate); + } + } else { + if (result) { + this.walkStatement(statement.consequent); + } else if (statement.alternate) { + this.walkStatement(statement.alternate); + } + } + } + + prewalkLabeledStatement(statement) { + this.prewalkStatement(statement.body); + } + + walkLabeledStatement(statement) { + const hook = this.hooks.label.get(statement.label.name); + if (hook !== undefined) { + const result = hook.call(statement); + if (result === true) return; + } + this.walkStatement(statement.body); + } + + prewalkWithStatement(statement) { + this.prewalkStatement(statement.body); + } + + walkWithStatement(statement) { + this.walkExpression(statement.object); + this.walkStatement(statement.body); + } + + prewalkSwitchStatement(statement) { + this.prewalkSwitchCases(statement.cases); + } + + walkSwitchStatement(statement) { + this.walkExpression(statement.discriminant); + this.walkSwitchCases(statement.cases); + } + + walkTerminatingStatement(statement) { + if (statement.argument) this.walkExpression(statement.argument); + } + + walkReturnStatement(statement) { + this.walkTerminatingStatement(statement); + } + + walkThrowStatement(statement) { + this.walkTerminatingStatement(statement); + } + + prewalkTryStatement(statement) { + this.prewalkStatement(statement.block); + } + + walkTryStatement(statement) { + if (this.scope.inTry) { + this.walkStatement(statement.block); + } else { + this.scope.inTry = true; + this.walkStatement(statement.block); + this.scope.inTry = false; + } + if (statement.handler) this.walkCatchClause(statement.handler); + if (statement.finalizer) this.walkStatement(statement.finalizer); + } + + prewalkWhileStatement(statement) { + this.prewalkStatement(statement.body); + } + + walkWhileStatement(statement) { + this.walkExpression(statement.test); + this.walkStatement(statement.body); + } + + prewalkDoWhileStatement(statement) { + this.prewalkStatement(statement.body); + } + + walkDoWhileStatement(statement) { + this.walkStatement(statement.body); + this.walkExpression(statement.test); + } + + prewalkForStatement(statement) { + if (statement.init) { + if (statement.init.type === "VariableDeclaration") { + this.prewalkStatement(statement.init); + } + } + this.prewalkStatement(statement.body); + } + + walkForStatement(statement) { + if (statement.init) { + if (statement.init.type === "VariableDeclaration") { + this.walkStatement(statement.init); + } else { + this.walkExpression(statement.init); + } + } + if (statement.test) { + this.walkExpression(statement.test); + } + if (statement.update) { + this.walkExpression(statement.update); + } + this.walkStatement(statement.body); + } + + prewalkForInStatement(statement) { + if (statement.left.type === "VariableDeclaration") { + this.prewalkVariableDeclaration(statement.left); + } + this.prewalkStatement(statement.body); + } + + walkForInStatement(statement) { + if (statement.left.type === "VariableDeclaration") { + this.walkVariableDeclaration(statement.left); + } else { + this.walkPattern(statement.left); + } + this.walkExpression(statement.right); + this.walkStatement(statement.body); + } + + prewalkForOfStatement(statement) { + if (statement.left.type === "VariableDeclaration") { + this.prewalkVariableDeclaration(statement.left); + } + this.prewalkStatement(statement.body); + } + + walkForOfStatement(statement) { + if (statement.left.type === "VariableDeclaration") { + this.walkVariableDeclaration(statement.left); + } else { + this.walkPattern(statement.left); + } + this.walkExpression(statement.right); + this.walkStatement(statement.body); + } + + // Declarations + prewalkFunctionDeclaration(statement) { + if (statement.id) { + this.scope.renames.set(statement.id.name, null); + this.scope.definitions.add(statement.id.name); + } + } + + walkFunctionDeclaration(statement) { + const wasTopLevel = this.scope.topLevelScope; + this.scope.topLevelScope = false; + this.inScope(statement.params, () => { + for (const param of statement.params) { + this.walkPattern(param); + } + if (statement.body.type === "BlockStatement") { + this.detectStrictMode(statement.body.body); + this.prewalkStatement(statement.body); + this.walkStatement(statement.body); + } else { + this.walkExpression(statement.body); + } + }); + this.scope.topLevelScope = wasTopLevel; + } + + prewalkImportDeclaration(statement) { + const source = statement.source.value; + this.hooks.import.call(statement, source); + for (const specifier of statement.specifiers) { + const name = specifier.local.name; + this.scope.renames.set(name, null); + this.scope.definitions.add(name); + switch (specifier.type) { + case "ImportDefaultSpecifier": + this.hooks.importSpecifier.call(statement, source, "default", name); + break; + case "ImportSpecifier": + this.hooks.importSpecifier.call( + statement, + source, + specifier.imported.name, + name + ); + break; + case "ImportNamespaceSpecifier": + this.hooks.importSpecifier.call(statement, source, null, name); + break; + } + } + } + + prewalkExportNamedDeclaration(statement) { + let source; + if (statement.source) { + source = statement.source.value; + this.hooks.exportImport.call(statement, source); + } else { + this.hooks.export.call(statement); + } + if (statement.declaration) { + if ( + !this.hooks.exportDeclaration.call(statement, statement.declaration) + ) { + const originalDefinitions = this.scope.definitions; + const tracker = new TrackingSet(this.scope.definitions); + this.scope.definitions = tracker; + this.prewalkStatement(statement.declaration); + const newDefs = Array.from(tracker.getAddedItems()); + this.scope.definitions = originalDefinitions; + for (let index = newDefs.length - 1; index >= 0; index--) { + const def = newDefs[index]; + this.hooks.exportSpecifier.call(statement, def, def, index); + } + } + } + if (statement.specifiers) { + for ( + let specifierIndex = 0; + specifierIndex < statement.specifiers.length; + specifierIndex++ + ) { + const specifier = statement.specifiers[specifierIndex]; + switch (specifier.type) { + case "ExportSpecifier": { + const name = specifier.exported.name; + if (source) { + this.hooks.exportImportSpecifier.call( + statement, + source, + specifier.local.name, + name, + specifierIndex + ); + } else { + this.hooks.exportSpecifier.call( + statement, + specifier.local.name, + name, + specifierIndex + ); + } + break; + } + } + } + } + } + + walkExportNamedDeclaration(statement) { + if (statement.declaration) { + this.walkStatement(statement.declaration); + } + } + + prewalkExportDefaultDeclaration(statement) { + if (statement.declaration.id) { + const originalDefinitions = this.scope.definitions; + const tracker = new TrackingSet(this.scope.definitions); + this.scope.definitions = tracker; + this.prewalkStatement(statement.declaration); + const newDefs = Array.from(tracker.getAddedItems()); + this.scope.definitions = originalDefinitions; + for (let index = 0, len = newDefs.length; index < len; index++) { + const def = newDefs[index]; + this.hooks.exportSpecifier.call(statement, def, "default"); + } + } + } + + walkExportDefaultDeclaration(statement) { + this.hooks.export.call(statement); + if ( + statement.declaration.id && + statement.declaration.type !== "FunctionExpression" && + statement.declaration.type !== "ClassExpression" + ) { + if ( + !this.hooks.exportDeclaration.call(statement, statement.declaration) + ) { + this.walkStatement(statement.declaration); + } + } else { + // Acorn parses `export default function() {}` as `FunctionDeclaration` and + // `export default class {}` as `ClassDeclaration`, both with `id = null`. + // These nodes must be treated as expressions. + if (statement.declaration.type === "FunctionDeclaration") { + this.walkFunctionDeclaration(statement.declaration); + } else if (statement.declaration.type === "ClassDeclaration") { + this.walkClassDeclaration(statement.declaration); + } else { + this.walkExpression(statement.declaration); + } + if (!this.hooks.exportExpression.call(statement, statement.declaration)) { + this.hooks.exportSpecifier.call( + statement, + statement.declaration, + "default" + ); + } + } + } + + prewalkExportAllDeclaration(statement) { + const source = statement.source.value; + this.hooks.exportImport.call(statement, source); + this.hooks.exportImportSpecifier.call(statement, source, null, null, 0); + } + + prewalkVariableDeclaration(statement) { + const hookMap = + statement.kind === "const" + ? this.hooks.varDeclarationConst + : statement.kind === "let" + ? this.hooks.varDeclarationLet + : this.hooks.varDeclarationVar; + for (const declarator of statement.declarations) { + switch (declarator.type) { + case "VariableDeclarator": { + this.enterPattern(declarator.id, (name, decl) => { + let hook = hookMap.get(name); + if (hook === undefined || !hook.call(decl)) { + hook = this.hooks.varDeclaration.get(name); + if (hook === undefined || !hook.call(decl)) { + this.scope.renames.set(name, null); + this.scope.definitions.add(name); + } + } + }); + break; + } + } + } + } + + walkVariableDeclaration(statement) { + for (const declarator of statement.declarations) { + switch (declarator.type) { + case "VariableDeclarator": { + const renameIdentifier = + declarator.init && this.getRenameIdentifier(declarator.init); + if (renameIdentifier && declarator.id.type === "Identifier") { + const hook = this.hooks.canRename.get(renameIdentifier); + if (hook !== undefined && hook.call(declarator.init)) { + // renaming with "var a = b;" + const hook = this.hooks.rename.get(renameIdentifier); + if (hook === undefined || !hook.call(declarator.init)) { + this.scope.renames.set( + declarator.id.name, + this.scope.renames.get(renameIdentifier) || renameIdentifier + ); + this.scope.definitions.delete(declarator.id.name); + } + break; + } + } + this.walkPattern(declarator.id); + if (declarator.init) this.walkExpression(declarator.init); + break; + } + } + } + } + + prewalkClassDeclaration(statement) { + if (statement.id) { + this.scope.renames.set(statement.id.name, null); + this.scope.definitions.add(statement.id.name); + } + } + + walkClassDeclaration(statement) { + this.walkClass(statement); + } + + prewalkSwitchCases(switchCases) { + for (let index = 0, len = switchCases.length; index < len; index++) { + const switchCase = switchCases[index]; + this.prewalkStatements(switchCase.consequent); + } + } + + walkSwitchCases(switchCases) { + for (let index = 0, len = switchCases.length; index < len; index++) { + const switchCase = switchCases[index]; + + if (switchCase.test) { + this.walkExpression(switchCase.test); + } + this.walkStatements(switchCase.consequent); + } + } + + walkCatchClause(catchClause) { + // Error binding is optional in catch clause since ECMAScript 2019 + const errorBinding = + catchClause.param === null ? EMPTY_ARRAY : [catchClause.param]; + + this.inScope(errorBinding, () => { + this.prewalkStatement(catchClause.body); + this.walkStatement(catchClause.body); + }); + } + + walkPattern(pattern) { + switch (pattern.type) { + case "ArrayPattern": + this.walkArrayPattern(pattern); + break; + case "AssignmentPattern": + this.walkAssignmentPattern(pattern); + break; + case "MemberExpression": + this.walkMemberExpression(pattern); + break; + case "ObjectPattern": + this.walkObjectPattern(pattern); + break; + case "RestElement": + this.walkRestElement(pattern); + break; + } + } + + walkAssignmentPattern(pattern) { + this.walkExpression(pattern.right); + this.walkPattern(pattern.left); + } + + walkObjectPattern(pattern) { + for (let i = 0, len = pattern.properties.length; i < len; i++) { + const prop = pattern.properties[i]; + if (prop) { + if (prop.computed) this.walkExpression(prop.key); + if (prop.value) this.walkPattern(prop.value); + } + } + } + + walkArrayPattern(pattern) { + for (let i = 0, len = pattern.elements.length; i < len; i++) { + const element = pattern.elements[i]; + if (element) this.walkPattern(element); + } + } + + walkRestElement(pattern) { + this.walkPattern(pattern.argument); + } + + walkExpressions(expressions) { + for (const expression of expressions) { + if (expression) { + this.walkExpression(expression); + } + } + } + + walkExpression(expression) { + switch (expression.type) { + case "ArrayExpression": + this.walkArrayExpression(expression); + break; + case "ArrowFunctionExpression": + this.walkArrowFunctionExpression(expression); + break; + case "AssignmentExpression": + this.walkAssignmentExpression(expression); + break; + case "AwaitExpression": + this.walkAwaitExpression(expression); + break; + case "BinaryExpression": + this.walkBinaryExpression(expression); + break; + case "CallExpression": + this.walkCallExpression(expression); + break; + case "ClassExpression": + this.walkClassExpression(expression); + break; + case "ConditionalExpression": + this.walkConditionalExpression(expression); + break; + case "FunctionExpression": + this.walkFunctionExpression(expression); + break; + case "Identifier": + this.walkIdentifier(expression); + break; + case "LogicalExpression": + this.walkLogicalExpression(expression); + break; + case "MemberExpression": + this.walkMemberExpression(expression); + break; + case "NewExpression": + this.walkNewExpression(expression); + break; + case "ObjectExpression": + this.walkObjectExpression(expression); + break; + case "SequenceExpression": + this.walkSequenceExpression(expression); + break; + case "SpreadElement": + this.walkSpreadElement(expression); + break; + case "TaggedTemplateExpression": + this.walkTaggedTemplateExpression(expression); + break; + case "TemplateLiteral": + this.walkTemplateLiteral(expression); + break; + case "ThisExpression": + this.walkThisExpression(expression); + break; + case "UnaryExpression": + this.walkUnaryExpression(expression); + break; + case "UpdateExpression": + this.walkUpdateExpression(expression); + break; + case "YieldExpression": + this.walkYieldExpression(expression); + break; + } + } + + walkAwaitExpression(expression) { + this.walkExpression(expression.argument); + } + + walkArrayExpression(expression) { + if (expression.elements) { + this.walkExpressions(expression.elements); + } + } + + walkSpreadElement(expression) { + if (expression.argument) { + this.walkExpression(expression.argument); + } + } + + walkObjectExpression(expression) { + for ( + let propIndex = 0, len = expression.properties.length; + propIndex < len; + propIndex++ + ) { + const prop = expression.properties[propIndex]; + if (prop.type === "SpreadElement") { + this.walkExpression(prop.argument); + continue; + } + if (prop.computed) { + this.walkExpression(prop.key); + } + if (prop.shorthand) { + this.scope.inShorthand = true; + } + this.walkExpression(prop.value); + if (prop.shorthand) { + this.scope.inShorthand = false; + } + } + } + + walkFunctionExpression(expression) { + const wasTopLevel = this.scope.topLevelScope; + this.scope.topLevelScope = false; + this.inScope(expression.params, () => { + for (const param of expression.params) { + this.walkPattern(param); + } + if (expression.body.type === "BlockStatement") { + this.detectStrictMode(expression.body.body); + this.prewalkStatement(expression.body); + this.walkStatement(expression.body); + } else { + this.walkExpression(expression.body); + } + }); + this.scope.topLevelScope = wasTopLevel; + } + + walkArrowFunctionExpression(expression) { + this.inScope(expression.params, () => { + for (const param of expression.params) { + this.walkPattern(param); + } + if (expression.body.type === "BlockStatement") { + this.detectStrictMode(expression.body.body); + this.prewalkStatement(expression.body); + this.walkStatement(expression.body); + } else { + this.walkExpression(expression.body); + } + }); + } + + walkSequenceExpression(expression) { + if (expression.expressions) this.walkExpressions(expression.expressions); + } + + walkUpdateExpression(expression) { + this.walkExpression(expression.argument); + } + + walkUnaryExpression(expression) { + if (expression.operator === "typeof") { + const exprName = this.getNameForExpression(expression.argument); + if (exprName && exprName.free) { + const hook = this.hooks.typeof.get(exprName.name); + if (hook !== undefined) { + const result = hook.call(expression); + if (result === true) return; + } + } + } + this.walkExpression(expression.argument); + } + + walkLeftRightExpression(expression) { + this.walkExpression(expression.left); + this.walkExpression(expression.right); + } + + walkBinaryExpression(expression) { + this.walkLeftRightExpression(expression); + } + + walkLogicalExpression(expression) { + this.walkLeftRightExpression(expression); + } + + walkAssignmentExpression(expression) { + const renameIdentifier = this.getRenameIdentifier(expression.right); + if (expression.left.type === "Identifier" && renameIdentifier) { + const hook = this.hooks.canRename.get(renameIdentifier); + if (hook !== undefined && hook.call(expression.right)) { + // renaming "a = b;" + const hook = this.hooks.rename.get(renameIdentifier); + if (hook === undefined || !hook.call(expression.right)) { + this.scope.renames.set(expression.left.name, renameIdentifier); + this.scope.definitions.delete(expression.left.name); + } + return; + } + } + if (expression.left.type === "Identifier") { + const assignedHook = this.hooks.assigned.get(expression.left.name); + if (assignedHook === undefined || !assignedHook.call(expression)) { + this.walkExpression(expression.right); + } + this.scope.renames.set(expression.left.name, null); + const assignHook = this.hooks.assign.get(expression.left.name); + if (assignHook === undefined || !assignHook.call(expression)) { + this.walkExpression(expression.left); + } + return; + } + this.walkExpression(expression.right); + this.walkPattern(expression.left); + this.enterPattern(expression.left, (name, decl) => { + this.scope.renames.set(name, null); + }); + } + + walkConditionalExpression(expression) { + const result = this.hooks.expressionConditionalOperator.call(expression); + if (result === undefined) { + this.walkExpression(expression.test); + this.walkExpression(expression.consequent); + if (expression.alternate) { + this.walkExpression(expression.alternate); + } + } else { + if (result) { + this.walkExpression(expression.consequent); + } else if (expression.alternate) { + this.walkExpression(expression.alternate); + } + } + } + + walkNewExpression(expression) { + const callee = this.evaluateExpression(expression.callee); + if (callee.isIdentifier()) { + const hook = this.hooks.new.get(callee.identifier); + if (hook !== undefined) { + const result = hook.call(expression); + if (result === true) { + return; + } + } + } + + this.walkExpression(expression.callee); + if (expression.arguments) { + this.walkExpressions(expression.arguments); + } + } + + walkYieldExpression(expression) { + if (expression.argument) { + this.walkExpression(expression.argument); + } + } + + walkTemplateLiteral(expression) { + if (expression.expressions) { + this.walkExpressions(expression.expressions); + } + } + + walkTaggedTemplateExpression(expression) { + if (expression.tag) { + this.walkExpression(expression.tag); + } + if (expression.quasi && expression.quasi.expressions) { + this.walkExpressions(expression.quasi.expressions); + } + } + + walkClassExpression(expression) { + this.walkClass(expression); + } + + _walkIIFE(functionExpression, options, currentThis) { + const renameArgOrThis = argOrThis => { + const renameIdentifier = this.getRenameIdentifier(argOrThis); + if (renameIdentifier) { + const hook = this.hooks.canRename.get(renameIdentifier); + if (hook !== undefined && hook.call(argOrThis)) { + const hook = this.hooks.rename.get(renameIdentifier); + if (hook === undefined || !hook.call(argOrThis)) { + return renameIdentifier; + } + } + } + this.walkExpression(argOrThis); + }; + const params = functionExpression.params; + const renameThis = currentThis ? renameArgOrThis(currentThis) : null; + const args = options.map(renameArgOrThis); + const wasTopLevel = this.scope.topLevelScope; + this.scope.topLevelScope = false; + this.inScope(params.filter((identifier, idx) => !args[idx]), () => { + if (renameThis) { + this.scope.renames.set("this", renameThis); + } + for (let i = 0; i < args.length; i++) { + const param = args[i]; + if (!param) continue; + if (!params[i] || params[i].type !== "Identifier") continue; + this.scope.renames.set(params[i].name, param); + } + if (functionExpression.body.type === "BlockStatement") { + this.prewalkStatement(functionExpression.body); + this.walkStatement(functionExpression.body); + } else { + this.walkExpression(functionExpression.body); + } + }); + this.scope.topLevelScope = wasTopLevel; + } + + walkCallExpression(expression) { + if ( + expression.callee.type === "MemberExpression" && + expression.callee.object.type === "FunctionExpression" && + !expression.callee.computed && + (expression.callee.property.name === "call" || + expression.callee.property.name === "bind") && + expression.arguments.length > 0 + ) { + // (function(…) { }.call/bind(?, …)) + this._walkIIFE( + expression.callee.object, + expression.arguments.slice(1), + expression.arguments[0] + ); + } else if (expression.callee.type === "FunctionExpression") { + // (function(…) { }(…)) + this._walkIIFE(expression.callee, expression.arguments, null); + } else if (expression.callee.type === "Import") { + let result = this.hooks.importCall.call(expression); + if (result === true) return; + + if (expression.arguments) this.walkExpressions(expression.arguments); + } else { + const callee = this.evaluateExpression(expression.callee); + if (callee.isIdentifier()) { + const callHook = this.hooks.call.get(callee.identifier); + if (callHook !== undefined) { + let result = callHook.call(expression); + if (result === true) return; + } + let identifier = callee.identifier.replace(/\.[^.]+$/, ""); + if (identifier !== callee.identifier) { + const callAnyHook = this.hooks.callAnyMember.get(identifier); + if (callAnyHook !== undefined) { + let result = callAnyHook.call(expression); + if (result === true) return; + } + } + } + + if (expression.callee) this.walkExpression(expression.callee); + if (expression.arguments) this.walkExpressions(expression.arguments); + } + } + + walkMemberExpression(expression) { + const exprName = this.getNameForExpression(expression); + if (exprName && exprName.free) { + const expressionHook = this.hooks.expression.get(exprName.name); + if (expressionHook !== undefined) { + const result = expressionHook.call(expression); + if (result === true) return; + } + const expressionAnyMemberHook = this.hooks.expressionAnyMember.get( + exprName.nameGeneral + ); + if (expressionAnyMemberHook !== undefined) { + const result = expressionAnyMemberHook.call(expression); + if (result === true) return; + } + } + this.walkExpression(expression.object); + if (expression.computed === true) this.walkExpression(expression.property); + } + + walkThisExpression(expression) { + const expressionHook = this.hooks.expression.get("this"); + if (expressionHook !== undefined) { + expressionHook.call(expression); + } + } + + walkIdentifier(expression) { + if (!this.scope.definitions.has(expression.name)) { + const hook = this.hooks.expression.get( + this.scope.renames.get(expression.name) || expression.name + ); + if (hook !== undefined) { + const result = hook.call(expression); + if (result === true) return; + } + } + } + + inScope(params, fn) { + const oldScope = this.scope; + this.scope = { + topLevelScope: oldScope.topLevelScope, + inTry: false, + inShorthand: false, + isStrict: oldScope.isStrict, + definitions: oldScope.definitions.createChild(), + renames: oldScope.renames.createChild() + }; + + this.scope.renames.set("this", null); + + for (const param of params) { + if (typeof param !== "string") { + this.enterPattern(param, param => { + this.scope.renames.set(param, null); + this.scope.definitions.add(param); + }); + } else if (param) { + this.scope.renames.set(param, null); + this.scope.definitions.add(param); + } + } + + fn(); + this.scope = oldScope; + } + + detectStrictMode(statements) { + const isStrict = + statements.length >= 1 && + statements[0].type === "ExpressionStatement" && + statements[0].expression.type === "Literal" && + statements[0].expression.value === "use strict"; + if (isStrict) { + this.scope.isStrict = true; + } + } + + enterPattern(pattern, onIdent) { + if (!pattern) return; + switch (pattern.type) { + case "ArrayPattern": + this.enterArrayPattern(pattern, onIdent); + break; + case "AssignmentPattern": + this.enterAssignmentPattern(pattern, onIdent); + break; + case "Identifier": + this.enterIdentifier(pattern, onIdent); + break; + case "ObjectPattern": + this.enterObjectPattern(pattern, onIdent); + break; + case "RestElement": + this.enterRestElement(pattern, onIdent); + break; + } + } + + enterIdentifier(pattern, onIdent) { + onIdent(pattern.name, pattern); + } + + enterObjectPattern(pattern, onIdent) { + for ( + let propIndex = 0, len = pattern.properties.length; + propIndex < len; + propIndex++ + ) { + const prop = pattern.properties[propIndex]; + this.enterPattern(prop.value, onIdent); + } + } + + enterArrayPattern(pattern, onIdent) { + for ( + let elementIndex = 0, len = pattern.elements.length; + elementIndex < len; + elementIndex++ + ) { + const element = pattern.elements[elementIndex]; + this.enterPattern(element, onIdent); + } + } + + enterRestElement(pattern, onIdent) { + this.enterPattern(pattern.argument, onIdent); + } + + enterAssignmentPattern(pattern, onIdent) { + this.enterPattern(pattern.left, onIdent); + } + + evaluateExpression(expression) { + try { + const hook = this.hooks.evaluate.get(expression.type); + if (hook !== undefined) { + const result = hook.call(expression); + if (result !== undefined) return result; + } + } catch (e) { + console.warn(e); + // ignore error + } + return new BasicEvaluatedExpression().setRange(expression.range); + } + + parseString(expression) { + switch (expression.type) { + case "BinaryExpression": + if (expression.operator === "+") { + return ( + this.parseString(expression.left) + + this.parseString(expression.right) + ); + } + break; + case "Literal": + return expression.value + ""; + } + throw new Error( + expression.type + " is not supported as parameter for require" + ); + } + + parseCalculatedString(expression) { + switch (expression.type) { + case "BinaryExpression": + if (expression.operator === "+") { + const left = this.parseCalculatedString(expression.left); + const right = this.parseCalculatedString(expression.right); + if (left.code) { + return { + range: left.range, + value: left.value, + code: true, + conditional: false + }; + } else if (right.code) { + return { + range: [ + left.range[0], + right.range ? right.range[1] : left.range[1] + ], + value: left.value + right.value, + code: true, + conditional: false + }; + } else { + return { + range: [left.range[0], right.range[1]], + value: left.value + right.value, + code: false, + conditional: false + }; + } + } + break; + case "ConditionalExpression": { + const consequent = this.parseCalculatedString(expression.consequent); + const alternate = this.parseCalculatedString(expression.alternate); + const items = []; + if (consequent.conditional) { + items.push(...consequent.conditional); + } else if (!consequent.code) { + items.push(consequent); + } else { + break; + } + if (alternate.conditional) { + items.push(...alternate.conditional); + } else if (!alternate.code) { + items.push(alternate); + } else { + break; + } + return { + range: undefined, + value: "", + code: true, + conditional: items + }; + } + case "Literal": + return { + range: expression.range, + value: expression.value + "", + code: false, + conditional: false + }; + } + return { + range: undefined, + value: "", + code: true, + conditional: false + }; + } + + parse(source, initialState) { + let ast; + let comments; + if (typeof source === "object" && source !== null) { + ast = source; + comments = source.comments; + } else { + comments = []; + ast = Parser.parse(source, { + sourceType: this.sourceType, + onComment: comments + }); + } + + const oldScope = this.scope; + const oldState = this.state; + const oldComments = this.comments; + this.scope = { + topLevelScope: true, + inTry: false, + inShorthand: false, + isStrict: false, + definitions: new StackedSetMap(), + renames: new StackedSetMap() + }; + const state = (this.state = initialState || {}); + this.comments = comments; + if (this.hooks.program.call(ast, comments) === undefined) { + this.detectStrictMode(ast.body); + this.prewalkStatements(ast.body); + this.walkStatements(ast.body); + } + this.scope = oldScope; + this.state = oldState; + this.comments = oldComments; + return state; + } + + evaluate(source) { + const ast = Parser.parse("(" + source + ")", { + sourceType: this.sourceType, + locations: false + }); + if (ast.body.length !== 1 || ast.body[0].type !== "ExpressionStatement") { + throw new Error("evaluate: Source is not a expression"); + } + return this.evaluateExpression(ast.body[0].expression); + } + + getComments(range) { + return this.comments.filter( + comment => comment.range[0] >= range[0] && comment.range[1] <= range[1] + ); + } + + parseCommentOptions(range) { + const comments = this.getComments(range); + if (comments.length === 0) { + return EMPTY_COMMENT_OPTIONS; + } + let options = {}; + let errors = []; + for (const comment of comments) { + const { value } = comment; + if (value && webpackCommentRegExp.test(value)) { + // try compile only if webpack options comment is present + try { + const val = vm.runInNewContext(`(function(){return {${value}};})()`); + Object.assign(options, val); + } catch (e) { + e.comment = comment; + errors.push(e); + } + } + } + return { options, errors }; + } + + getNameForExpression(expression) { + let expr = expression; + const exprName = []; + while ( + expr.type === "MemberExpression" && + expr.property.type === (expr.computed ? "Literal" : "Identifier") + ) { + exprName.push(expr.computed ? expr.property.value : expr.property.name); + expr = expr.object; + } + let free; + if (expr.type === "Identifier") { + free = !this.scope.definitions.has(expr.name); + exprName.push(this.scope.renames.get(expr.name) || expr.name); + } else if ( + expr.type === "ThisExpression" && + this.scope.renames.get("this") + ) { + free = true; + exprName.push(this.scope.renames.get("this")); + } else if (expr.type === "ThisExpression") { + free = this.scope.topLevelScope; + exprName.push("this"); + } else { + return null; + } + let prefix = ""; + for (let i = exprName.length - 1; i >= 2; i--) { + prefix += exprName[i] + "."; + } + if (exprName.length > 1) { + prefix += exprName[1]; + } + const name = prefix ? prefix + "." + exprName[0] : exprName[0]; + const nameGeneral = prefix; + return { + name, + nameGeneral, + free + }; + } + + static parse(code, options) { + const type = options ? options.sourceType : "module"; + const parserOptions = Object.assign( + Object.create(null), + defaultParserOptions, + options + ); + + if (type === "auto") { + parserOptions.sourceType = "module"; + } + + let ast; + let error; + let threw = false; + try { + ast = acorn.parse(code, parserOptions); + } catch (e) { + error = e; + threw = true; + } + + if (threw && type === "auto") { + parserOptions.sourceType = "script"; + if (Array.isArray(parserOptions.onComment)) { + parserOptions.onComment.length = 0; + } + try { + ast = acorn.parse(code, parserOptions); + threw = false; + } catch (e) { + threw = true; + } + } + + if (threw) { + throw error; + } + + return ast; + } +} + +// TODO remove in webpack 5 +Object.defineProperty(Parser.prototype, "getCommentOptions", { + configurable: false, + value: util.deprecate( + /** + * @deprecated + * @param {TODO} range Range + * @returns {void} + * @this {Parser} + */ + function(range) { + return this.parseCommentOptions(range).options; + }, + "Parser.getCommentOptions: Use Parser.parseCommentOptions(range) instead" + ) +}); + +module.exports = Parser; diff --git a/node_modules/webpack/lib/ParserHelpers.js b/node_modules/webpack/lib/ParserHelpers.js index 64a0e9996..5248f12fe 100644 --- a/node_modules/webpack/lib/ParserHelpers.js +++ b/node_modules/webpack/lib/ParserHelpers.js @@ -1,85 +1,103 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const path = require("path");
-
-const BasicEvaluatedExpression = require("./BasicEvaluatedExpression");
-const ConstDependency = require("./dependencies/ConstDependency");
-const UnsupportedFeatureWarning = require("./UnsupportedFeatureWarning");
-
-const ParserHelpers = exports;
-
-ParserHelpers.addParsedVariableToModule = function(parser, name, expression) {
- if(!parser.state.current.addVariable) return false;
- var deps = [];
- parser.parse(expression, {
- current: {
- addDependency: function(dep) {
- dep.userRequest = name;
- deps.push(dep);
- }
- },
- module: parser.state.module
- });
- parser.state.current.addVariable(name, expression, deps);
- return true;
-};
-
-ParserHelpers.requireFileAsExpression = function(context, pathToModule) {
- var moduleJsPath = path.relative(context, pathToModule);
- if(!/^[A-Z]:/i.test(moduleJsPath)) {
- moduleJsPath = "./" + moduleJsPath.replace(/\\/g, "/");
- }
- return "require(" + JSON.stringify(moduleJsPath) + ")";
-};
-
-ParserHelpers.toConstantDependency = function(value) {
- return function constDependency(expr) {
- var dep = new ConstDependency(value, expr.range);
- dep.loc = expr.loc;
- this.state.current.addDependency(dep);
- return true;
- };
-};
-
-ParserHelpers.evaluateToString = function(value) {
- return function stringExpression(expr) {
- return new BasicEvaluatedExpression().setString(value).setRange(expr.range);
- };
-};
-
-ParserHelpers.evaluateToBoolean = function(value) {
- return function booleanExpression(expr) {
- return new BasicEvaluatedExpression().setBoolean(value).setRange(expr.range);
- };
-};
-
-ParserHelpers.evaluateToIdentifier = function(identifier, truthy) {
- return function identifierExpression(expr) {
- let evex = new BasicEvaluatedExpression().setIdentifier(identifier).setRange(expr.range);
- if(truthy === true) evex = evex.setTruthy();
- else if(truthy === false) evex = evex.setFalsy();
- return evex;
- };
-};
-
-ParserHelpers.expressionIsUnsupported = function(message) {
- return function unsupportedExpression(expr) {
- var dep = new ConstDependency("(void 0)", expr.range);
- dep.loc = expr.loc;
- this.state.current.addDependency(dep);
- if(!this.state.module) return;
- this.state.module.warnings.push(new UnsupportedFeatureWarning(this.state.module, message));
- return true;
- };
-};
-
-ParserHelpers.skipTraversal = function skipTraversal() {
- return true;
-};
-
-ParserHelpers.approve = function approve() {
- return true;
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const path = require("path"); + +const BasicEvaluatedExpression = require("./BasicEvaluatedExpression"); +const ConstDependency = require("./dependencies/ConstDependency"); +const UnsupportedFeatureWarning = require("./UnsupportedFeatureWarning"); + +const ParserHelpers = exports; + +ParserHelpers.addParsedVariableToModule = (parser, name, expression) => { + if (!parser.state.current.addVariable) return false; + var deps = []; + parser.parse(expression, { + current: { + addDependency: dep => { + dep.userRequest = name; + deps.push(dep); + } + }, + module: parser.state.module + }); + parser.state.current.addVariable(name, expression, deps); + return true; +}; + +ParserHelpers.requireFileAsExpression = (context, pathToModule) => { + var moduleJsPath = path.relative(context, pathToModule); + if (!/^[A-Z]:/i.test(moduleJsPath)) { + moduleJsPath = "./" + moduleJsPath.replace(/\\/g, "/"); + } + return "require(" + JSON.stringify(moduleJsPath) + ")"; +}; + +ParserHelpers.toConstantDependency = (parser, value) => { + return function constDependency(expr) { + var dep = new ConstDependency(value, expr.range, false); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + return true; + }; +}; + +ParserHelpers.toConstantDependencyWithWebpackRequire = (parser, value) => { + return function constDependencyWithWebpackRequire(expr) { + var dep = new ConstDependency(value, expr.range, true); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + return true; + }; +}; + +ParserHelpers.evaluateToString = value => { + return function stringExpression(expr) { + return new BasicEvaluatedExpression().setString(value).setRange(expr.range); + }; +}; + +ParserHelpers.evaluateToBoolean = value => { + return function booleanExpression(expr) { + return new BasicEvaluatedExpression() + .setBoolean(value) + .setRange(expr.range); + }; +}; + +ParserHelpers.evaluateToIdentifier = (identifier, truthy) => { + return function identifierExpression(expr) { + let evex = new BasicEvaluatedExpression() + .setIdentifier(identifier) + .setRange(expr.range); + if (truthy === true) { + evex = evex.setTruthy(); + } else if (truthy === false) { + evex = evex.setFalsy(); + } + return evex; + }; +}; + +ParserHelpers.expressionIsUnsupported = (parser, message) => { + return function unsupportedExpression(expr) { + var dep = new ConstDependency("(void 0)", expr.range, false); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + if (!parser.state.module) return; + parser.state.module.warnings.push( + new UnsupportedFeatureWarning(parser.state.module, message, expr.loc) + ); + return true; + }; +}; + +ParserHelpers.skipTraversal = function skipTraversal() { + return true; +}; + +ParserHelpers.approve = function approve() { + return true; +}; diff --git a/node_modules/webpack/lib/PrefetchPlugin.js b/node_modules/webpack/lib/PrefetchPlugin.js index 4f45d33f7..cc9d17c0c 100644 --- a/node_modules/webpack/lib/PrefetchPlugin.js +++ b/node_modules/webpack/lib/PrefetchPlugin.js @@ -1,31 +1,37 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const PrefetchDependency = require("./dependencies/PrefetchDependency");
-
-class PrefetchPlugin {
-
- constructor(context, request) {
- if(!request) {
- this.request = context;
- } else {
- this.context = context;
- this.request = request;
- }
- }
-
- apply(compiler) {
- compiler.plugin("compilation", (compilation, params) => {
- const normalModuleFactory = params.normalModuleFactory;
-
- compilation.dependencyFactories.set(PrefetchDependency, normalModuleFactory);
- });
- compiler.plugin("make", (compilation, callback) => {
- compilation.prefetch(this.context || compiler.context, new PrefetchDependency(this.request), callback);
- });
- }
-
-}
-module.exports = PrefetchPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const PrefetchDependency = require("./dependencies/PrefetchDependency"); + +class PrefetchPlugin { + constructor(context, request) { + if (!request) { + this.request = context; + } else { + this.context = context; + this.request = request; + } + } + + apply(compiler) { + compiler.hooks.compilation.tap( + "PrefetchPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + PrefetchDependency, + normalModuleFactory + ); + } + ); + compiler.hooks.make.tapAsync("PrefetchPlugin", (compilation, callback) => { + compilation.prefetch( + this.context || compiler.context, + new PrefetchDependency(this.request), + callback + ); + }); + } +} +module.exports = PrefetchPlugin; diff --git a/node_modules/webpack/lib/ProgressPlugin.js b/node_modules/webpack/lib/ProgressPlugin.js index b0828d8a8..a8612932d 100644 --- a/node_modules/webpack/lib/ProgressPlugin.js +++ b/node_modules/webpack/lib/ProgressPlugin.js @@ -1,192 +1,246 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-class ProgressPlugin {
-
- constructor(options) {
- if(typeof options === "function") {
- options = {
- handler: options
- };
- }
- options = options || {};
- this.profile = options.profile;
- this.handler = options.handler;
- }
-
- apply(compiler) {
- const handler = this.handler || defaultHandler;
- const profile = this.profile;
- if(compiler.compilers) {
- const states = new Array(compiler.compilers.length);
- compiler.compilers.forEach(function(compiler, idx) {
- compiler.apply(new ProgressPlugin(function(p, msg) {
- states[idx] = Array.prototype.slice.apply(arguments);
- handler.apply(null, [
- states.map(state => state && state[0] || 0).reduce((a, b) => a + b) / states.length,
- `[${idx}] ${msg}`
- ].concat(Array.prototype.slice.call(arguments, 2)));
- }));
- });
- } else {
- let lastModulesCount = 0;
- let moduleCount = 500;
- let doneModules = 0;
- const activeModules = [];
-
- const update = function update(module) {
- handler(
- 0.1 + (doneModules / Math.max(lastModulesCount, moduleCount)) * 0.6,
- "building modules",
- `${doneModules}/${moduleCount} modules`,
- `${activeModules.length} active`,
- activeModules[activeModules.length - 1]
- );
- };
-
- const moduleDone = function moduleDone(module) {
- doneModules++;
- const ident = module.identifier();
- if(ident) {
- const idx = activeModules.indexOf(ident);
- if(idx >= 0) activeModules.splice(idx, 1);
- }
- update();
- };
- compiler.plugin("compilation", function(compilation) {
- if(compilation.compiler.isChild()) return;
- lastModulesCount = moduleCount;
- moduleCount = 0;
- doneModules = 0;
- handler(0, "compiling");
- compilation.plugin("build-module", function(module) {
- moduleCount++;
- const ident = module.identifier();
- if(ident) {
- activeModules.push(ident);
- }
- update();
- });
- compilation.plugin("failed-module", moduleDone);
- compilation.plugin("succeed-module", moduleDone);
- const syncHooks = {
- "seal": [0.71, "sealing"],
- "optimize": [0.72, "optimizing"],
- "optimize-modules-basic": [0.73, "basic module optimization"],
- "optimize-modules": [0.74, "module optimization"],
- "optimize-modules-advanced": [0.75, "advanced module optimization"],
- "optimize-chunks-basic": [0.76, "basic chunk optimization"],
- "optimize-chunks": [0.77, "chunk optimization"],
- "optimize-chunks-advanced": [0.78, "advanced chunk optimization"],
- // optimize-tree
- "optimize-chunk-modules": [0.80, "chunk modules optimization"],
- "optimize-chunk-modules-advanced": [0.81, "advanced chunk modules optimization"],
- "revive-modules": [0.82, "module reviving"],
- "optimize-module-order": [0.83, "module order optimization"],
- "optimize-module-ids": [0.84, "module id optimization"],
- "revive-chunks": [0.85, "chunk reviving"],
- "optimize-chunk-order": [0.86, "chunk order optimization"],
- "optimize-chunk-ids": [0.87, "chunk id optimization"],
- "before-hash": [0.88, "hashing"],
- "before-module-assets": [0.89, "module assets processing"],
- "before-chunk-assets": [0.90, "chunk assets processing"],
- "additional-chunk-assets": [0.91, "additional chunk assets processing"],
- "record": [0.92, "recording"]
- };
- Object.keys(syncHooks).forEach(name => {
- let pass = 0;
- const settings = syncHooks[name];
- compilation.plugin(name, () => {
- if(pass++ > 0)
- handler(settings[0], settings[1], `pass ${pass}`);
- else
- handler(settings[0], settings[1]);
- });
- });
- compilation.plugin("optimize-tree", (chunks, modules, callback) => {
- handler(0.79, "module and chunk tree optimization");
- callback();
- });
- compilation.plugin("additional-assets", callback => {
- handler(0.91, "additional asset processing");
- callback();
- });
- compilation.plugin("optimize-chunk-assets", (chunks, callback) => {
- handler(0.92, "chunk asset optimization");
- callback();
- });
- compilation.plugin("optimize-assets", (assets, callback) => {
- handler(0.94, "asset optimization");
- callback();
- });
- });
- compiler.plugin("emit", (compilation, callback) => {
- handler(0.95, "emitting");
- callback();
- });
- compiler.plugin("done", () => {
- handler(1, "");
- });
- }
-
- let lineCaretPosition = 0,
- lastState, lastStateTime;
-
- function defaultHandler(percentage, msg) {
- let state = msg;
- const details = Array.prototype.slice.call(arguments, 2);
- if(percentage < 1) {
- percentage = Math.floor(percentage * 100);
- msg = `${percentage}% ${msg}`;
- if(percentage < 100) {
- msg = ` ${msg}`;
- }
- if(percentage < 10) {
- msg = ` ${msg}`;
- }
- details.forEach(detail => {
- if(!detail) return;
- if(detail.length > 40) {
- detail = `...${detail.substr(detail.length - 37)}`;
- }
- msg += ` ${detail}`;
- });
- }
- if(profile) {
- state = state.replace(/^\d+\/\d+\s+/, "");
- if(percentage === 0) {
- lastState = null;
- lastStateTime = Date.now();
- } else if(state !== lastState || percentage === 1) {
- const now = Date.now();
- if(lastState) {
- const stateMsg = `${now - lastStateTime}ms ${lastState}`;
- goToLineStart(stateMsg);
- process.stderr.write(stateMsg + "\n");
- lineCaretPosition = 0;
- }
- lastState = state;
- lastStateTime = now;
- }
- }
- goToLineStart(msg);
- process.stderr.write(msg);
- }
-
- function goToLineStart(nextMessage) {
- let str = "";
- for(; lineCaretPosition > nextMessage.length; lineCaretPosition--) {
- str += "\b \b";
- }
- for(var i = 0; i < lineCaretPosition; i++) {
- str += "\b";
- }
- lineCaretPosition = nextMessage.length;
- if(str) process.stderr.write(str);
- }
- }
-}
-module.exports = ProgressPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const createDefaultHandler = profile => { + let lineCaretPosition = 0; + let lastState; + let lastStateTime; + + const defaultHandler = (percentage, msg, ...args) => { + let state = msg; + const details = args; + if (percentage < 1) { + percentage = Math.floor(percentage * 100); + msg = `${percentage}% ${msg}`; + if (percentage < 100) { + msg = ` ${msg}`; + } + if (percentage < 10) { + msg = ` ${msg}`; + } + for (let detail of details) { + if (!detail) continue; + if (detail.length > 40) { + detail = `...${detail.substr(detail.length - 39)}`; + } + msg += ` ${detail}`; + } + } + if (profile) { + state = state.replace(/^\d+\/\d+\s+/, ""); + if (percentage === 0) { + lastState = null; + lastStateTime = Date.now(); + } else if (state !== lastState || percentage === 1) { + const now = Date.now(); + if (lastState) { + const stateMsg = `${now - lastStateTime}ms ${lastState}`; + goToLineStart(stateMsg); + process.stderr.write(stateMsg + "\n"); + lineCaretPosition = 0; + } + lastState = state; + lastStateTime = now; + } + } + goToLineStart(msg); + process.stderr.write(msg); + }; + + const goToLineStart = nextMessage => { + let str = ""; + for (; lineCaretPosition > nextMessage.length; lineCaretPosition--) { + str += "\b \b"; + } + for (var i = 0; i < lineCaretPosition; i++) { + str += "\b"; + } + lineCaretPosition = nextMessage.length; + if (str) process.stderr.write(str); + }; + + return defaultHandler; +}; + +class ProgressPlugin { + constructor(options) { + if (typeof options === "function") { + options = { + handler: options + }; + } + options = options || {}; + this.profile = options.profile; + this.handler = options.handler; + } + + apply(compiler) { + const handler = this.handler || createDefaultHandler(this.profile); + if (compiler.compilers) { + const states = new Array(compiler.compilers.length); + compiler.compilers.forEach((compiler, idx) => { + new ProgressPlugin((p, msg, ...args) => { + states[idx] = [p, msg, ...args]; + handler( + states + .map(state => (state && state[0]) || 0) + .reduce((a, b) => a + b) / states.length, + `[${idx}] ${msg}`, + ...args + ); + }).apply(compiler); + }); + } else { + let lastModulesCount = 0; + let moduleCount = 500; + let doneModules = 0; + const activeModules = []; + + const update = module => { + handler( + 0.1 + (doneModules / Math.max(lastModulesCount, moduleCount)) * 0.6, + "building modules", + `${doneModules}/${moduleCount} modules`, + `${activeModules.length} active`, + activeModules[activeModules.length - 1] + ); + }; + + const moduleDone = module => { + doneModules++; + const ident = module.identifier(); + if (ident) { + const idx = activeModules.indexOf(ident); + if (idx >= 0) activeModules.splice(idx, 1); + } + update(); + }; + compiler.hooks.compilation.tap("ProgressPlugin", compilation => { + if (compilation.compiler.isChild()) return; + lastModulesCount = moduleCount; + moduleCount = 0; + doneModules = 0; + handler(0, "compiling"); + compilation.hooks.buildModule.tap("ProgressPlugin", module => { + moduleCount++; + const ident = module.identifier(); + if (ident) { + activeModules.push(ident); + } + update(); + }); + compilation.hooks.failedModule.tap("ProgressPlugin", moduleDone); + compilation.hooks.succeedModule.tap("ProgressPlugin", moduleDone); + const hooks = { + finishModules: "finish module graph", + seal: "sealing", + optimizeDependenciesBasic: "basic dependencies optimization", + optimizeDependencies: "dependencies optimization", + optimizeDependenciesAdvanced: "advanced dependencies optimization", + afterOptimizeDependencies: "after dependencies optimization", + optimize: "optimizing", + optimizeModulesBasic: "basic module optimization", + optimizeModules: "module optimization", + optimizeModulesAdvanced: "advanced module optimization", + afterOptimizeModules: "after module optimization", + optimizeChunksBasic: "basic chunk optimization", + optimizeChunks: "chunk optimization", + optimizeChunksAdvanced: "advanced chunk optimization", + afterOptimizeChunks: "after chunk optimization", + optimizeTree: "module and chunk tree optimization", + afterOptimizeTree: "after module and chunk tree optimization", + optimizeChunkModulesBasic: "basic chunk modules optimization", + optimizeChunkModules: "chunk modules optimization", + optimizeChunkModulesAdvanced: "advanced chunk modules optimization", + afterOptimizeChunkModules: "after chunk modules optimization", + reviveModules: "module reviving", + optimizeModuleOrder: "module order optimization", + advancedOptimizeModuleOrder: "advanced module order optimization", + beforeModuleIds: "before module ids", + moduleIds: "module ids", + optimizeModuleIds: "module id optimization", + afterOptimizeModuleIds: "module id optimization", + reviveChunks: "chunk reviving", + optimizeChunkOrder: "chunk order optimization", + beforeChunkIds: "before chunk ids", + optimizeChunkIds: "chunk id optimization", + afterOptimizeChunkIds: "after chunk id optimization", + recordModules: "record modules", + recordChunks: "record chunks", + beforeHash: "hashing", + afterHash: "after hashing", + recordHash: "record hash", + beforeModuleAssets: "module assets processing", + beforeChunkAssets: "chunk assets processing", + additionalChunkAssets: "additional chunk assets processing", + record: "recording", + additionalAssets: "additional asset processing", + optimizeChunkAssets: "chunk asset optimization", + afterOptimizeChunkAssets: "after chunk asset optimization", + optimizeAssets: "asset optimization", + afterOptimizeAssets: "after asset optimization", + afterSeal: "after seal" + }; + const numberOfHooks = Object.keys(hooks).length; + Object.keys(hooks).forEach((name, idx) => { + const title = hooks[name]; + const percentage = (idx / numberOfHooks) * 0.25 + 0.7; + compilation.hooks[name].intercept({ + name: "ProgressPlugin", + context: true, + call: () => { + handler(percentage, title); + }, + tap: (context, tap) => { + if (context) { + // p is percentage from 0 to 1 + // args is any number of messages in a hierarchical matter + context.reportProgress = (p, ...args) => { + handler(percentage, title, tap.name, ...args); + }; + } + handler(percentage, title, tap.name); + } + }); + }); + }); + compiler.hooks.emit.intercept({ + name: "ProgressPlugin", + context: true, + call: () => { + handler(0.95, "emitting"); + }, + tap: (context, tap) => { + if (context) { + context.reportProgress = (p, ...args) => { + handler(0.95, "emitting", tap.name, ...args); + }; + } + handler(0.95, "emitting", tap.name); + } + }); + compiler.hooks.afterEmit.intercept({ + name: "ProgressPlugin", + context: true, + call: () => { + handler(0.98, "after emitting"); + }, + tap: (context, tap) => { + if (context) { + context.reportProgress = (p, ...args) => { + handler(0.98, "after emitting", tap.name, ...args); + }; + } + handler(0.98, "after emitting", tap.name); + } + }); + compiler.hooks.done.tap("ProgressPlugin", () => { + handler(1, ""); + }); + } + } +} +module.exports = ProgressPlugin; diff --git a/node_modules/webpack/lib/ProvidePlugin.js b/node_modules/webpack/lib/ProvidePlugin.js index fff352a4b..b09d8c864 100644 --- a/node_modules/webpack/lib/ProvidePlugin.js +++ b/node_modules/webpack/lib/ProvidePlugin.js @@ -1,55 +1,86 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const ParserHelpers = require("./ParserHelpers");
-const ConstDependency = require("./dependencies/ConstDependency");
-
-const NullFactory = require("./NullFactory");
-
-class ProvidePlugin {
- constructor(definitions) {
- this.definitions = definitions;
- }
-
- apply(compiler) {
- const definitions = this.definitions;
- compiler.plugin("compilation", (compilation, params) => {
- compilation.dependencyFactories.set(ConstDependency, new NullFactory());
- compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
- params.normalModuleFactory.plugin("parser", (parser, parserOptions) => {
- Object.keys(definitions).forEach(name => {
- var request = [].concat(definitions[name]);
- var splittedName = name.split(".");
- if(splittedName.length > 0) {
- splittedName.slice(1).forEach((_, i) => {
- const name = splittedName.slice(0, i + 1).join(".");
- parser.plugin(`can-rename ${name}`, ParserHelpers.approve);
- });
- }
- parser.plugin(`expression ${name}`, function(expr) {
- let nameIdentifier = name;
- const scopedName = name.indexOf(".") >= 0;
- let expression = `require(${JSON.stringify(request[0])})`;
- if(scopedName) {
- nameIdentifier = `__webpack_provided_${name.replace(/\./g, "_dot_")}`;
- }
- if(request.length > 1) {
- expression += request.slice(1).map(r => `[${JSON.stringify(r)}]`).join("");
- }
- if(!ParserHelpers.addParsedVariableToModule(this, nameIdentifier, expression)) {
- return false;
- }
- if(scopedName) {
- ParserHelpers.toConstantDependency(nameIdentifier).bind(this)(expr);
- }
- return true;
- });
- });
- });
- });
- }
-}
-module.exports = ProvidePlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const ParserHelpers = require("./ParserHelpers"); +const ConstDependency = require("./dependencies/ConstDependency"); + +const NullFactory = require("./NullFactory"); + +class ProvidePlugin { + constructor(definitions) { + this.definitions = definitions; + } + + apply(compiler) { + const definitions = this.definitions; + compiler.hooks.compilation.tap( + "ProvidePlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set(ConstDependency, new NullFactory()); + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); + const handler = (parser, parserOptions) => { + Object.keys(definitions).forEach(name => { + var request = [].concat(definitions[name]); + var splittedName = name.split("."); + if (splittedName.length > 0) { + splittedName.slice(1).forEach((_, i) => { + const name = splittedName.slice(0, i + 1).join("."); + parser.hooks.canRename + .for(name) + .tap("ProvidePlugin", ParserHelpers.approve); + }); + } + parser.hooks.expression.for(name).tap("ProvidePlugin", expr => { + let nameIdentifier = name; + const scopedName = name.includes("."); + let expression = `require(${JSON.stringify(request[0])})`; + if (scopedName) { + nameIdentifier = `__webpack_provided_${name.replace( + /\./g, + "_dot_" + )}`; + } + if (request.length > 1) { + expression += request + .slice(1) + .map(r => `[${JSON.stringify(r)}]`) + .join(""); + } + if ( + !ParserHelpers.addParsedVariableToModule( + parser, + nameIdentifier, + expression + ) + ) { + return false; + } + if (scopedName) { + ParserHelpers.toConstantDependency(parser, nameIdentifier)( + expr + ); + } + return true; + }); + }); + }; + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("ProvidePlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("ProvidePlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("ProvidePlugin", handler); + } + ); + } +} +module.exports = ProvidePlugin; diff --git a/node_modules/webpack/lib/RawModule.js b/node_modules/webpack/lib/RawModule.js index d937cafc0..ab3fd3ab5 100644 --- a/node_modules/webpack/lib/RawModule.js +++ b/node_modules/webpack/lib/RawModule.js @@ -1,54 +1,56 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const Module = require("./Module");
-const OriginalSource = require("webpack-sources").OriginalSource;
-const RawSource = require("webpack-sources").RawSource;
-
-module.exports = class RawModule extends Module {
-
- constructor(source, identifier, readableIdentifier) {
- super();
- this.sourceStr = source;
- this.identifierStr = identifier || this.sourceStr;
- this.readableIdentifierStr = readableIdentifier || this.identifierStr;
- this.cacheable = true;
- this.built = false;
- }
-
- identifier() {
- return this.identifierStr;
- }
-
- size() {
- return this.sourceStr.length;
- }
-
- readableIdentifier(requestShortener) {
- return requestShortener.shorten(this.readableIdentifierStr);
- }
-
- needRebuild() {
- return false;
- }
-
- build(options, compilations, resolver, fs, callback) {
- this.builtTime = Date.now();
- callback();
- }
-
- source() {
- if(this.useSourceMap)
- return new OriginalSource(this.sourceStr, this.identifier());
- else
- return new RawSource(this.sourceStr);
- }
-
- updateHash(hash) {
- hash.update(this.sourceStr);
- super.updateHash(hash);
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Module = require("./Module"); +const { OriginalSource, RawSource } = require("webpack-sources"); + +module.exports = class RawModule extends Module { + constructor(source, identifier, readableIdentifier) { + super("javascript/dynamic", null); + this.sourceStr = source; + this.identifierStr = identifier || this.sourceStr; + this.readableIdentifierStr = readableIdentifier || this.identifierStr; + this.built = false; + } + + identifier() { + return this.identifierStr; + } + + size() { + return this.sourceStr.length; + } + + readableIdentifier(requestShortener) { + return requestShortener.shorten(this.readableIdentifierStr); + } + + needRebuild() { + return false; + } + + build(options, compilations, resolver, fs, callback) { + this.built = true; + this.buildMeta = {}; + this.buildInfo = { + cacheable: true + }; + callback(); + } + + source() { + if (this.useSourceMap) { + return new OriginalSource(this.sourceStr, this.identifier()); + } else { + return new RawSource(this.sourceStr); + } + } + + updateHash(hash) { + hash.update(this.sourceStr); + super.updateHash(hash); + } +}; diff --git a/node_modules/webpack/lib/RecordIdsPlugin.js b/node_modules/webpack/lib/RecordIdsPlugin.js index a4d53085b..88c6a9a3c 100644 --- a/node_modules/webpack/lib/RecordIdsPlugin.js +++ b/node_modules/webpack/lib/RecordIdsPlugin.js @@ -1,117 +1,230 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const identifierUtils = require("./util/identifier");
-
-class RecordIdsPlugin {
-
- apply(compiler) {
- compiler.plugin("compilation", compilation => {
- compilation.plugin("record-modules", (modules, records) => {
- if(!records.modules) records.modules = {};
- if(!records.modules.byIdentifier) records.modules.byIdentifier = {};
- if(!records.modules.usedIds) records.modules.usedIds = {};
- modules.forEach(function(module) {
- if(!module.portableId) module.portableId = identifierUtils.makePathsRelative(compiler.context, module.identifier());
- const identifier = module.portableId;
- records.modules.byIdentifier[identifier] = module.id;
- records.modules.usedIds[module.id] = module.id;
- });
- });
- compilation.plugin("revive-modules", (modules, records) => {
- if(!records.modules) return;
- if(records.modules.byIdentifier) {
- const usedIds = {};
- modules.forEach(function(module) {
- if(module.id !== null) return;
- if(!module.portableId) module.portableId = identifierUtils.makePathsRelative(compiler.context, module.identifier());
- const identifier = module.portableId;
- const id = records.modules.byIdentifier[identifier];
- if(id === undefined) return;
- if(usedIds[id]) return;
- usedIds[id] = true;
- module.id = id;
- });
- }
- compilation.usedModuleIds = records.modules.usedIds;
- });
-
- function getDepBlockIdent(chunk, block) {
- const ident = [];
- if(block.chunks.length > 1)
- ident.push(block.chunks.indexOf(chunk));
- while(block.parent) {
- const p = block.parent;
- const idx = p.blocks.indexOf(block);
- const l = p.blocks.length - 1;
- ident.push(`${idx}/${l}`);
- block = block.parent;
- }
- if(!block.identifier) return null;
- ident.push(identifierUtils.makePathsRelative(compiler.context, block.identifier()));
- return ident.reverse().join(":");
- }
- compilation.plugin("record-chunks", (chunks, records) => {
- records.nextFreeChunkId = compilation.nextFreeChunkId;
- if(!records.chunks) records.chunks = {};
- if(!records.chunks.byName) records.chunks.byName = {};
- if(!records.chunks.byBlocks) records.chunks.byBlocks = {};
- records.chunks.usedIds = {};
- chunks.forEach(chunk => {
- const name = chunk.name;
- const blockIdents = chunk.blocks.map(getDepBlockIdent.bind(null, chunk)).filter(Boolean);
- if(name) records.chunks.byName[name] = chunk.id;
- blockIdents.forEach((blockIdent) => {
- records.chunks.byBlocks[blockIdent] = chunk.id;
- });
- records.chunks.usedIds[chunk.id] = chunk.id;
- });
- });
- compilation.plugin("revive-chunks", (chunks, records) => {
- if(!records.chunks) return;
- const usedIds = {};
- if(records.chunks.byName) {
- chunks.forEach(function(chunk) {
- if(chunk.id !== null) return;
- if(!chunk.name) return;
- const id = records.chunks.byName[chunk.name];
- if(id === undefined) return;
- if(usedIds[id]) return;
- usedIds[id] = true;
- chunk.id = id;
- });
- }
- if(records.chunks.byBlocks) {
- const argumentedChunks = chunks.filter(chunk => chunk.id === null).map(chunk => ({
- chunk,
- blockIdents: chunk.blocks.map(getDepBlockIdent.bind(null, chunk)).filter(Boolean)
- })).filter(arg => arg.blockIdents.length > 0);
- let blockIdentsCount = {};
- argumentedChunks.forEach((arg, idx) => {
- arg.blockIdents.forEach(blockIdent => {
- const id = records.chunks.byBlocks[blockIdent];
- if(typeof id !== "number") return;
- const accessor = `${id}:${idx}`;
- blockIdentsCount[accessor] = (blockIdentsCount[accessor] || 0) + 1;
- });
- });
- blockIdentsCount = Object.keys(blockIdentsCount).map(accessor => [blockIdentsCount[accessor]].concat(accessor.split(":").map(Number))).sort((a, b) => b[0] - a[0]);
- blockIdentsCount.forEach(function(arg) {
- const id = arg[1];
- if(usedIds[id]) return;
- const idx = arg[2];
- const chunk = argumentedChunks[idx].chunk;
- if(chunk.id !== null) return;
- usedIds[id] = true;
- chunk.id = id;
- });
- }
- compilation.usedChunkIds = records.chunks.usedIds;
- });
- });
- }
-}
-module.exports = RecordIdsPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const identifierUtils = require("./util/identifier"); + +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Chunk")} Chunk */ +/** @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 {Record<number, 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; + compiler.hooks.compilation.tap("RecordIdsPlugin", compilation => { + compilation.hooks.recordModules.tap( + "RecordIdsPlugin", + /** + * @param {Module[]} modules the modules array + * @param {Records} records the records object + * @returns {void} + */ + (modules, records) => { + if (!records.modules) records.modules = {}; + if (!records.modules.byIdentifier) records.modules.byIdentifier = {}; + if (!records.modules.usedIds) records.modules.usedIds = {}; + for (const module of modules) { + if (typeof module.id !== "number") continue; + const identifier = portableIds + ? identifierUtils.makePathsRelative( + compiler.context, + module.identifier(), + compilation.cache + ) + : module.identifier(); + records.modules.byIdentifier[identifier] = module.id; + records.modules.usedIds[module.id] = module.id; + } + } + ); + compilation.hooks.reviveModules.tap( + "RecordIdsPlugin", + /** + * @param {Module[]} modules the modules array + * @param {Records} records the records object + * @returns {void} + */ + (modules, records) => { + if (!records.modules) return; + if (records.modules.byIdentifier) { + /** @type {Set<number>} */ + const usedIds = new Set(); + for (const module of modules) { + if (module.id !== null) continue; + const identifier = portableIds + ? identifierUtils.makePathsRelative( + compiler.context, + module.identifier(), + compilation.cache + ) + : module.identifier(); + const id = records.modules.byIdentifier[identifier]; + if (id === undefined) continue; + if (usedIds.has(id)) continue; + usedIds.add(id); + module.id = id; + } + } + if (Array.isArray(records.modules.usedIds)) { + compilation.usedModuleIds = new Set(records.modules.usedIds); + } + } + ); + + /** + * @param {Module} module the module + * @returns {string} the (portable) identifier + */ + const getModuleIdentifier = module => { + if (portableIds) { + return identifierUtils.makePathsRelative( + compiler.context, + module.identifier(), + compilation.cache + ); + } + return module.identifier(); + }; + + /** + * @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); + 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" && + origin.loc.start + ) { + sources.push( + `${index} ${getModuleIdentifier( + origin.module + )} ${JSON.stringify(origin.loc.start)}` + ); + } + } + } + } + return sources; + }; + + compilation.hooks.recordChunks.tap( + "RecordIdsPlugin", + /** + * @param {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(); + } + ); + compilation.hooks.reviveChunks.tap( + "RecordIdsPlugin", + /** + * @param {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; + } + } + if (records.chunks.bySource) { + for (const chunk of chunks) { + 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; + break; + } + } + } + if (Array.isArray(records.chunks.usedIds)) { + compilation.usedChunkIds = new Set(records.chunks.usedIds); + } + } + ); + }); + } +} +module.exports = RecordIdsPlugin; diff --git a/node_modules/webpack/lib/RequestShortener.js b/node_modules/webpack/lib/RequestShortener.js index 0dd27a7d2..7b007816a 100644 --- a/node_modules/webpack/lib/RequestShortener.js +++ b/node_modules/webpack/lib/RequestShortener.js @@ -1,63 +1,83 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const path = require("path");
-const NORMALIZE_SLASH_DIRECTION_REGEXP = /\\/g;
-const PATH_CHARS_REGEXP = /[-[\]{}()*+?.,\\^$|#\s]/g;
-const SEPARATOR_REGEXP = /[/\\]$/;
-const FRONT_OR_BACK_BANG_REGEXP = /^!|!$/g;
-const INDEX_JS_REGEXP = /\/index.js(!|\?|\(query\))/g;
-
-const normalizeBackSlashDirection = (request) => {
- return request.replace(NORMALIZE_SLASH_DIRECTION_REGEXP, "/");
-};
-
-const createRegExpForPath = (path) => {
- const regexpTypePartial = path.replace(PATH_CHARS_REGEXP, "\\$&");
- return new RegExp(`(^|!)${regexpTypePartial}`, "g");
-};
-
-class RequestShortener {
- constructor(directory) {
- directory = normalizeBackSlashDirection(directory);
- if(SEPARATOR_REGEXP.test(directory)) directory = directory.substr(0, directory.length - 1);
-
- if(directory) {
- this.currentDirectoryRegExp = createRegExpForPath(directory);
- }
-
- const dirname = path.dirname(directory);
- const endsWithSeperator = SEPARATOR_REGEXP.test(dirname);
- const parentDirectory = endsWithSeperator ? dirname.substr(0, dirname.length - 1) : dirname;
- if(parentDirectory && parentDirectory !== directory) {
- this.parentDirectoryRegExp = createRegExpForPath(parentDirectory);
- }
-
- if(__dirname.length >= 2) {
- const buildins = normalizeBackSlashDirection(path.join(__dirname, ".."));
- const buildinsAsModule = this.currentDirectoryRegExp && this.currentDirectoryRegExp.test(buildins);
- this.buildinsAsModule = buildinsAsModule;
- this.buildinsRegExp = createRegExpForPath(buildins);
- }
- }
-
- shorten(request) {
- if(!request) return request;
- request = normalizeBackSlashDirection(request);
- if(this.buildinsAsModule && this.buildinsRegExp)
- request = request.replace(this.buildinsRegExp, "!(webpack)");
- if(this.currentDirectoryRegExp)
- request = request.replace(this.currentDirectoryRegExp, "!.");
- if(this.parentDirectoryRegExp)
- request = request.replace(this.parentDirectoryRegExp, "!..");
- if(!this.buildinsAsModule && this.buildinsRegExp)
- request = request.replace(this.buildinsRegExp, "!(webpack)");
- request = request.replace(INDEX_JS_REGEXP, "$1");
- return request.replace(FRONT_OR_BACK_BANG_REGEXP, "");
- }
-}
-
-module.exports = RequestShortener;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const path = require("path"); +const NORMALIZE_SLASH_DIRECTION_REGEXP = /\\/g; +const PATH_CHARS_REGEXP = /[-[\]{}()*+?.,\\^$|#\s]/g; +const SEPARATOR_REGEXP = /[/\\]$/; +const FRONT_OR_BACK_BANG_REGEXP = /^!|!$/g; +const INDEX_JS_REGEXP = /\/index.js(!|\?|\(query\))/g; +const MATCH_RESOURCE_REGEXP = /!=!/; + +const normalizeBackSlashDirection = request => { + return request.replace(NORMALIZE_SLASH_DIRECTION_REGEXP, "/"); +}; + +const createRegExpForPath = path => { + const regexpTypePartial = path.replace(PATH_CHARS_REGEXP, "\\$&"); + return new RegExp(`(^|!)${regexpTypePartial}`, "g"); +}; + +class RequestShortener { + constructor(directory) { + directory = normalizeBackSlashDirection(directory); + if (SEPARATOR_REGEXP.test(directory)) { + directory = directory.substr(0, directory.length - 1); + } + + if (directory) { + this.currentDirectoryRegExp = createRegExpForPath(directory); + } + + const dirname = path.dirname(directory); + const endsWithSeparator = SEPARATOR_REGEXP.test(dirname); + const parentDirectory = endsWithSeparator + ? dirname.substr(0, dirname.length - 1) + : dirname; + if (parentDirectory && parentDirectory !== directory) { + this.parentDirectoryRegExp = createRegExpForPath(parentDirectory); + } + + if (__dirname.length >= 2) { + const buildins = normalizeBackSlashDirection(path.join(__dirname, "..")); + const buildinsAsModule = + this.currentDirectoryRegExp && + this.currentDirectoryRegExp.test(buildins); + this.buildinsAsModule = buildinsAsModule; + this.buildinsRegExp = createRegExpForPath(buildins); + } + + this.cache = new Map(); + } + + shorten(request) { + if (!request) return request; + const cacheEntry = this.cache.get(request); + if (cacheEntry !== undefined) { + return cacheEntry; + } + let result = normalizeBackSlashDirection(request); + if (this.buildinsAsModule && this.buildinsRegExp) { + result = result.replace(this.buildinsRegExp, "!(webpack)"); + } + if (this.currentDirectoryRegExp) { + result = result.replace(this.currentDirectoryRegExp, "!."); + } + if (this.parentDirectoryRegExp) { + result = result.replace(this.parentDirectoryRegExp, "!.."); + } + if (!this.buildinsAsModule && this.buildinsRegExp) { + result = result.replace(this.buildinsRegExp, "!(webpack)"); + } + result = result.replace(INDEX_JS_REGEXP, "$1"); + result = result.replace(FRONT_OR_BACK_BANG_REGEXP, ""); + result = result.replace(MATCH_RESOURCE_REGEXP, " = "); + this.cache.set(request, result); + return result; + } +} + +module.exports = RequestShortener; diff --git a/node_modules/webpack/lib/RequireJsStuffPlugin.js b/node_modules/webpack/lib/RequireJsStuffPlugin.js index 92bc3fc91..632deefc2 100644 --- a/node_modules/webpack/lib/RequireJsStuffPlugin.js +++ b/node_modules/webpack/lib/RequireJsStuffPlugin.js @@ -1,31 +1,66 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const ParserHelpers = require("./ParserHelpers");
-const ConstDependency = require("./dependencies/ConstDependency");
-const NullFactory = require("./NullFactory");
-
-module.exports = class RequireJsStuffPlugin {
-
- apply(compiler) {
- compiler.plugin("compilation", function(compilation, params) {
- compilation.dependencyFactories.set(ConstDependency, new NullFactory());
- compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
- params.normalModuleFactory.plugin("parser", function(parser, parserOptions) {
-
- if(typeof parserOptions.requireJs !== "undefined" && !parserOptions.requireJs)
- return;
-
- parser.plugin("call require.config", ParserHelpers.toConstantDependency("undefined"));
- parser.plugin("call requirejs.config", ParserHelpers.toConstantDependency("undefined"));
-
- parser.plugin("expression require.version", ParserHelpers.toConstantDependency(JSON.stringify("0.0.0")));
- parser.plugin("expression requirejs.onError", ParserHelpers.toConstantDependency("__webpack_require__.oe"));
- });
- });
- }
-
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const ParserHelpers = require("./ParserHelpers"); +const ConstDependency = require("./dependencies/ConstDependency"); +const NullFactory = require("./NullFactory"); + +module.exports = class RequireJsStuffPlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "RequireJsStuffPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set(ConstDependency, new NullFactory()); + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); + const handler = (parser, parserOptions) => { + if (parserOptions.requireJs !== undefined && !parserOptions.requireJs) + return; + + parser.hooks.call + .for("require.config") + .tap( + "RequireJsStuffPlugin", + ParserHelpers.toConstantDependency(parser, "undefined") + ); + parser.hooks.call + .for("requirejs.config") + .tap( + "RequireJsStuffPlugin", + ParserHelpers.toConstantDependency(parser, "undefined") + ); + + parser.hooks.expression + .for("require.version") + .tap( + "RequireJsStuffPlugin", + ParserHelpers.toConstantDependency( + parser, + JSON.stringify("0.0.0") + ) + ); + parser.hooks.expression + .for("requirejs.onError") + .tap( + "RequireJsStuffPlugin", + ParserHelpers.toConstantDependencyWithWebpackRequire( + parser, + "__webpack_require__.oe" + ) + ); + }; + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("RequireJsStuffPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("RequireJsStuffPlugin", handler); + } + ); + } +}; diff --git a/node_modules/webpack/lib/RuleSet.js b/node_modules/webpack/lib/RuleSet.js index cb679b5f6..7ed8eba6f 100644 --- a/node_modules/webpack/lib/RuleSet.js +++ b/node_modules/webpack/lib/RuleSet.js @@ -1,444 +1,567 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-/*
-<rules>: <rule>
-<rules>: [<rule>]
-<rule>: {
- resource: {
- test: <condition>,
- include: <condition>,
- exclude: <condition>,
- },
- resource: <condition>, -> resource.test
- test: <condition>, -> resource.test
- include: <condition>, -> resource.include
- exclude: <condition>, -> resource.exclude
- resourceQuery: <condition>,
- compiler: <condition>,
- issuer: <condition>,
- use: "loader", -> use[0].loader
- loader: <>, -> use[0].loader
- loaders: <>, -> use
- options: {}, -> use[0].options,
- query: {}, -> options
- parser: {},
- use: [
- "loader" -> use[x].loader
- ],
- use: [
- {
- loader: "loader",
- options: {}
- }
- ],
- rules: [
- <rule>
- ],
- oneOf: [
- <rule>
- ]
-}
-
-<condition>: /regExp/
-<condition>: function(arg) {}
-<condition>: "starting"
-<condition>: [<condition>] // or
-<condition>: { and: [<condition>] }
-<condition>: { or: [<condition>] }
-<condition>: { not: [<condition>] }
-<condition>: { test: <condition>, include: <condition>, exclude: <condition> }
-
-
-normalized:
-
-{
- resource: function(),
- resourceQuery: function(),
- compiler: function(),
- issuer: function(),
- use: [
- {
- loader: string,
- options: string,
- <any>: <any>
- }
- ],
- rules: [<rule>],
- oneOf: [<rule>],
- <any>: <any>,
-}
-
-*/
-
-"use strict";
-
-module.exports = class RuleSet {
- constructor(rules) {
- this.references = Object.create(null);
- this.rules = RuleSet.normalizeRules(rules, this.references, "ref-");
- }
-
- static normalizeRules(rules, refs, ident) {
- if(Array.isArray(rules)) {
- return rules.map((rule, idx) => {
- return RuleSet.normalizeRule(rule, refs, `${ident}-${idx}`);
- });
- } else if(rules) {
- return [RuleSet.normalizeRule(rules, refs, ident)];
- } else {
- return [];
- }
- }
-
- static normalizeRule(rule, refs, ident) {
- if(typeof rule === "string")
- return {
- use: [{
- loader: rule
- }]
- };
- if(!rule)
- throw new Error("Unexcepted null when object was expected as rule");
- if(typeof rule !== "object")
- throw new Error("Unexcepted " + typeof rule + " when object was expected as rule (" + rule + ")");
-
- const newRule = {};
- let useSource;
- let resourceSource;
- let condition;
-
- if(rule.test || rule.include || rule.exclude) {
- checkResourceSource("test + include + exclude");
- condition = {
- test: rule.test,
- include: rule.include,
- exclude: rule.exclude
- };
- try {
- newRule.resource = RuleSet.normalizeCondition(condition);
- } catch(error) {
- throw new Error(RuleSet.buildErrorMessage(condition, error));
- }
- }
-
- if(rule.resource) {
- checkResourceSource("resource");
- try {
- newRule.resource = RuleSet.normalizeCondition(rule.resource);
- } catch(error) {
- throw new Error(RuleSet.buildErrorMessage(rule.resource, error));
- }
- }
-
- if(rule.resourceQuery) {
- try {
- newRule.resourceQuery = RuleSet.normalizeCondition(rule.resourceQuery);
- } catch(error) {
- throw new Error(RuleSet.buildErrorMessage(rule.resourceQuery, error));
- }
- }
-
- if(rule.compiler) {
- try {
- newRule.compiler = RuleSet.normalizeCondition(rule.compiler);
- } catch(error) {
- throw new Error(RuleSet.buildErrorMessage(rule.compiler, error));
- }
- }
-
- if(rule.issuer) {
- try {
- newRule.issuer = RuleSet.normalizeCondition(rule.issuer);
- } catch(error) {
- throw new Error(RuleSet.buildErrorMessage(rule.issuer, error));
- }
- }
-
- if(rule.loader && rule.loaders)
- throw new Error(RuleSet.buildErrorMessage(rule, new Error("Provided loader and loaders for rule (use only one of them)")));
-
- const loader = rule.loaders || rule.loader;
- if(typeof loader === "string" && !rule.options && !rule.query) {
- checkUseSource("loader");
- newRule.use = RuleSet.normalizeUse(loader.split("!"), ident);
- } else if(typeof loader === "string" && (rule.options || rule.query)) {
- checkUseSource("loader + options/query");
- newRule.use = RuleSet.normalizeUse({
- loader: loader,
- options: rule.options,
- query: rule.query
- }, ident);
- } else if(loader && (rule.options || rule.query)) {
- throw new Error(RuleSet.buildErrorMessage(rule, new Error("options/query cannot be used with loaders (use options for each array item)")));
- } else if(loader) {
- checkUseSource("loaders");
- newRule.use = RuleSet.normalizeUse(loader, ident);
- } else if(rule.options || rule.query) {
- throw new Error(RuleSet.buildErrorMessage(rule, new Error("options/query provided without loader (use loader + options)")));
- }
-
- if(rule.use) {
- checkUseSource("use");
- newRule.use = RuleSet.normalizeUse(rule.use, ident);
- }
-
- if(rule.rules)
- newRule.rules = RuleSet.normalizeRules(rule.rules, refs, `${ident}-rules`);
-
- if(rule.oneOf)
- newRule.oneOf = RuleSet.normalizeRules(rule.oneOf, refs, `${ident}-oneOf`);
-
- const keys = Object.keys(rule).filter((key) => {
- return ["resource", "resourceQuery", "compiler", "test", "include", "exclude", "issuer", "loader", "options", "query", "loaders", "use", "rules", "oneOf"].indexOf(key) < 0;
- });
- keys.forEach((key) => {
- newRule[key] = rule[key];
- });
-
- function checkUseSource(newSource) {
- if(useSource && useSource !== newSource)
- throw new Error(RuleSet.buildErrorMessage(rule, new Error("Rule can only have one result source (provided " + newSource + " and " + useSource + ")")));
- useSource = newSource;
- }
-
- function checkResourceSource(newSource) {
- if(resourceSource && resourceSource !== newSource)
- throw new Error(RuleSet.buildErrorMessage(rule, new Error("Rule can only have one resource source (provided " + newSource + " and " + resourceSource + ")")));
- resourceSource = newSource;
- }
-
- if(Array.isArray(newRule.use)) {
- newRule.use.forEach((item) => {
- if(item.ident) {
- refs[item.ident] = item.options;
- }
- });
- }
-
- return newRule;
- }
-
- static buildErrorMessage(condition, error) {
- const conditionAsText = JSON.stringify(condition, (key, value) => {
- return value === undefined ? "undefined" : value;
- }, 2);
- return error.message + " in " + conditionAsText;
- }
-
- static normalizeUse(use, ident) {
- if(Array.isArray(use)) {
- return use
- .map((item, idx) => RuleSet.normalizeUse(item, `${ident}-${idx}`))
- .reduce((arr, items) => arr.concat(items), []);
- }
- return [RuleSet.normalizeUseItem(use, ident)];
- }
-
- static normalizeUseItemFunction(use, data) {
- const result = use(data);
- if(typeof result === "string") {
- return RuleSet.normalizeUseItem(result);
- }
- return result;
- }
-
- static normalizeUseItemString(useItemString) {
- const idx = useItemString.indexOf("?");
- if(idx >= 0) {
- return {
- loader: useItemString.substr(0, idx),
- options: useItemString.substr(idx + 1)
- };
- }
- return {
- loader: useItemString
- };
- }
-
- static normalizeUseItem(item, ident) {
- if(typeof item === "function")
- return item;
-
- if(typeof item === "string") {
- return RuleSet.normalizeUseItemString(item);
- }
-
- const newItem = {};
-
- if(item.options && item.query)
- throw new Error("Provided options and query in use");
-
- if(!item.loader)
- throw new Error("No loader specified");
-
- newItem.options = item.options || item.query;
-
- if(typeof newItem.options === "object" && newItem.options) {
- if(newItem.options.ident)
- newItem.ident = newItem.options.ident;
- else
- newItem.ident = ident;
- }
-
- const keys = Object.keys(item).filter(function(key) {
- return ["options", "query"].indexOf(key) < 0;
- });
-
- keys.forEach(function(key) {
- newItem[key] = item[key];
- });
-
- return newItem;
- }
-
- static normalizeCondition(condition) {
- if(!condition)
- throw new Error("Expected condition but got falsy value");
- if(typeof condition === "string") {
- return str => str.indexOf(condition) === 0;
- }
- if(typeof condition === "function") {
- return condition;
- }
- if(condition instanceof RegExp) {
- return condition.test.bind(condition);
- }
- if(Array.isArray(condition)) {
- const items = condition.map(c => RuleSet.normalizeCondition(c));
- return orMatcher(items);
- }
- if(typeof condition !== "object")
- throw Error("Unexcepted " + typeof condition + " when condition was expected (" + condition + ")");
-
- const matchers = [];
- Object.keys(condition).forEach(key => {
- const value = condition[key];
- switch(key) {
- case "or":
- case "include":
- case "test":
- if(value)
- matchers.push(RuleSet.normalizeCondition(value));
- break;
- case "and":
- if(value) {
- const items = value.map(c => RuleSet.normalizeCondition(c));
- matchers.push(andMatcher(items));
- }
- break;
- case "not":
- case "exclude":
- if(value) {
- const matcher = RuleSet.normalizeCondition(value);
- matchers.push(notMatcher(matcher));
- }
- break;
- default:
- throw new Error("Unexcepted property " + key + " in condition");
- }
- });
- if(matchers.length === 0)
- throw new Error("Excepted condition but got " + condition);
- if(matchers.length === 1)
- return matchers[0];
- return andMatcher(matchers);
- }
-
- exec(data) {
- const result = [];
- this._run(data, {
- rules: this.rules
- }, result);
- return result;
- }
-
- _run(data, rule, result) {
- // test conditions
- if(rule.resource && !data.resource)
- return false;
- if(rule.resourceQuery && !data.resourceQuery)
- return false;
- if(rule.compiler && !data.compiler)
- return false;
- if(rule.issuer && !data.issuer)
- return false;
- if(rule.resource && !rule.resource(data.resource))
- return false;
- if(data.issuer && rule.issuer && !rule.issuer(data.issuer))
- return false;
- if(data.resourceQuery && rule.resourceQuery && !rule.resourceQuery(data.resourceQuery))
- return false;
- if(data.compiler && rule.compiler && !rule.compiler(data.compiler))
- return false;
-
- // apply
- const keys = Object.keys(rule).filter((key) => {
- return ["resource", "resourceQuery", "compiler", "issuer", "rules", "oneOf", "use", "enforce"].indexOf(key) < 0;
- });
- keys.forEach((key) => {
- result.push({
- type: key,
- value: rule[key]
- });
- });
-
- if(rule.use) {
- rule.use.forEach((use) => {
- result.push({
- type: "use",
- value: typeof use === "function" ? RuleSet.normalizeUseItemFunction(use, data) : use,
- enforce: rule.enforce
- });
- });
- }
-
- if(rule.rules) {
- for(let i = 0; i < rule.rules.length; i++) {
- this._run(data, rule.rules[i], result);
- }
- }
-
- if(rule.oneOf) {
- for(let i = 0; i < rule.oneOf.length; i++) {
- if(this._run(data, rule.oneOf[i], result))
- break;
- }
- }
-
- return true;
- }
-
- findOptionsByIdent(ident) {
- const options = this.references[ident];
- if(!options) throw new Error("Can't find options with ident '" + ident + "'");
- return options;
- }
-};
-
-function notMatcher(matcher) {
- return function(str) {
- return !matcher(str);
- };
-}
-
-function orMatcher(items) {
- return function(str) {
- for(let i = 0; i < items.length; i++) {
- if(items[i](str))
- return true;
- }
- return false;
- };
-}
-
-function andMatcher(items) {
- return function(str) {
- for(let i = 0; i < items.length; i++) {
- if(!items[i](str))
- return false;
- }
- return true;
- };
-}
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +/* +<rules>: <rule> +<rules>: [<rule>] +<rule>: { + resource: { + test: <condition>, + include: <condition>, + exclude: <condition>, + }, + resource: <condition>, -> resource.test + test: <condition>, -> resource.test + include: <condition>, -> resource.include + exclude: <condition>, -> resource.exclude + resourceQuery: <condition>, + compiler: <condition>, + issuer: <condition>, + use: "loader", -> use[0].loader + loader: <>, -> use[0].loader + loaders: <>, -> use + options: {}, -> use[0].options, + query: {}, -> options + parser: {}, + use: [ + "loader" -> use[x].loader + ], + use: [ + { + loader: "loader", + options: {} + } + ], + rules: [ + <rule> + ], + oneOf: [ + <rule> + ] +} + +<condition>: /regExp/ +<condition>: function(arg) {} +<condition>: "starting" +<condition>: [<condition>] // or +<condition>: { and: [<condition>] } +<condition>: { or: [<condition>] } +<condition>: { not: [<condition>] } +<condition>: { test: <condition>, include: <condition>, exclude: <condition> } + + +normalized: + +{ + resource: function(), + resourceQuery: function(), + compiler: function(), + issuer: function(), + use: [ + { + loader: string, + options: string, + <any>: <any> + } + ], + rules: [<rule>], + oneOf: [<rule>], + <any>: <any>, +} + +*/ + +"use strict"; + +const notMatcher = matcher => { + return str => { + return !matcher(str); + }; +}; + +const orMatcher = items => { + return str => { + for (let i = 0; i < items.length; i++) { + if (items[i](str)) return true; + } + return false; + }; +}; + +const andMatcher = items => { + return str => { + for (let i = 0; i < items.length; i++) { + if (!items[i](str)) return false; + } + return true; + }; +}; + +module.exports = class RuleSet { + constructor(rules) { + this.references = Object.create(null); + this.rules = RuleSet.normalizeRules(rules, this.references, "ref-"); + } + + static normalizeRules(rules, refs, ident) { + if (Array.isArray(rules)) { + return rules.map((rule, idx) => { + return RuleSet.normalizeRule(rule, refs, `${ident}-${idx}`); + }); + } else if (rules) { + return [RuleSet.normalizeRule(rules, refs, ident)]; + } else { + return []; + } + } + + static normalizeRule(rule, refs, ident) { + if (typeof rule === "string") { + return { + use: [ + { + loader: rule + } + ] + }; + } + if (!rule) { + throw new Error("Unexcepted null when object was expected as rule"); + } + if (typeof rule !== "object") { + throw new Error( + "Unexcepted " + + typeof rule + + " when object was expected as rule (" + + rule + + ")" + ); + } + + const newRule = {}; + let useSource; + let resourceSource; + let condition; + + const checkUseSource = newSource => { + if (useSource && useSource !== newSource) { + throw new Error( + RuleSet.buildErrorMessage( + rule, + new Error( + "Rule can only have one result source (provided " + + newSource + + " and " + + useSource + + ")" + ) + ) + ); + } + useSource = newSource; + }; + + const checkResourceSource = newSource => { + if (resourceSource && resourceSource !== newSource) { + throw new Error( + RuleSet.buildErrorMessage( + rule, + new Error( + "Rule can only have one resource source (provided " + + newSource + + " and " + + resourceSource + + ")" + ) + ) + ); + } + resourceSource = newSource; + }; + + if (rule.test || rule.include || rule.exclude) { + checkResourceSource("test + include + exclude"); + condition = { + test: rule.test, + include: rule.include, + exclude: rule.exclude + }; + try { + newRule.resource = RuleSet.normalizeCondition(condition); + } catch (error) { + throw new Error(RuleSet.buildErrorMessage(condition, error)); + } + } + + if (rule.resource) { + checkResourceSource("resource"); + try { + newRule.resource = RuleSet.normalizeCondition(rule.resource); + } catch (error) { + throw new Error(RuleSet.buildErrorMessage(rule.resource, error)); + } + } + + if (rule.realResource) { + try { + newRule.realResource = RuleSet.normalizeCondition(rule.realResource); + } catch (error) { + throw new Error(RuleSet.buildErrorMessage(rule.realResource, error)); + } + } + + if (rule.resourceQuery) { + try { + newRule.resourceQuery = RuleSet.normalizeCondition(rule.resourceQuery); + } catch (error) { + throw new Error(RuleSet.buildErrorMessage(rule.resourceQuery, error)); + } + } + + if (rule.compiler) { + try { + newRule.compiler = RuleSet.normalizeCondition(rule.compiler); + } catch (error) { + throw new Error(RuleSet.buildErrorMessage(rule.compiler, error)); + } + } + + if (rule.issuer) { + try { + newRule.issuer = RuleSet.normalizeCondition(rule.issuer); + } catch (error) { + throw new Error(RuleSet.buildErrorMessage(rule.issuer, error)); + } + } + + if (rule.loader && rule.loaders) { + throw new Error( + RuleSet.buildErrorMessage( + rule, + new Error( + "Provided loader and loaders for rule (use only one of them)" + ) + ) + ); + } + + const loader = rule.loaders || rule.loader; + if (typeof loader === "string" && !rule.options && !rule.query) { + checkUseSource("loader"); + newRule.use = RuleSet.normalizeUse(loader.split("!"), ident); + } else if (typeof loader === "string" && (rule.options || rule.query)) { + checkUseSource("loader + options/query"); + newRule.use = RuleSet.normalizeUse( + { + loader: loader, + options: rule.options, + query: rule.query + }, + ident + ); + } else if (loader && (rule.options || rule.query)) { + throw new Error( + RuleSet.buildErrorMessage( + rule, + new Error( + "options/query cannot be used with loaders (use options for each array item)" + ) + ) + ); + } else if (loader) { + checkUseSource("loaders"); + newRule.use = RuleSet.normalizeUse(loader, ident); + } else if (rule.options || rule.query) { + throw new Error( + RuleSet.buildErrorMessage( + rule, + new Error( + "options/query provided without loader (use loader + options)" + ) + ) + ); + } + + if (rule.use) { + checkUseSource("use"); + newRule.use = RuleSet.normalizeUse(rule.use, ident); + } + + if (rule.rules) { + newRule.rules = RuleSet.normalizeRules( + rule.rules, + refs, + `${ident}-rules` + ); + } + + if (rule.oneOf) { + newRule.oneOf = RuleSet.normalizeRules( + rule.oneOf, + refs, + `${ident}-oneOf` + ); + } + + const keys = Object.keys(rule).filter(key => { + return ![ + "resource", + "resourceQuery", + "compiler", + "test", + "include", + "exclude", + "issuer", + "loader", + "options", + "query", + "loaders", + "use", + "rules", + "oneOf" + ].includes(key); + }); + for (const key of keys) { + newRule[key] = rule[key]; + } + + if (Array.isArray(newRule.use)) { + for (const item of newRule.use) { + if (item.ident) { + refs[item.ident] = item.options; + } + } + } + + return newRule; + } + + static buildErrorMessage(condition, error) { + const conditionAsText = JSON.stringify( + condition, + (key, value) => { + return value === undefined ? "undefined" : value; + }, + 2 + ); + return error.message + " in " + conditionAsText; + } + + static normalizeUse(use, ident) { + if (typeof use === "function") { + return data => RuleSet.normalizeUse(use(data), ident); + } + if (Array.isArray(use)) { + return use + .map((item, idx) => RuleSet.normalizeUse(item, `${ident}-${idx}`)) + .reduce((arr, items) => arr.concat(items), []); + } + return [RuleSet.normalizeUseItem(use, ident)]; + } + + static normalizeUseItemString(useItemString) { + const idx = useItemString.indexOf("?"); + if (idx >= 0) { + return { + loader: useItemString.substr(0, idx), + options: useItemString.substr(idx + 1) + }; + } + return { + loader: useItemString, + options: undefined + }; + } + + static normalizeUseItem(item, ident) { + if (typeof item === "string") { + return RuleSet.normalizeUseItemString(item); + } + + const newItem = {}; + + if (item.options && item.query) { + throw new Error("Provided options and query in use"); + } + + if (!item.loader) { + throw new Error("No loader specified"); + } + + newItem.options = item.options || item.query; + + if (typeof newItem.options === "object" && newItem.options) { + if (newItem.options.ident) { + newItem.ident = newItem.options.ident; + } else { + newItem.ident = ident; + } + } + + const keys = Object.keys(item).filter(function(key) { + return !["options", "query"].includes(key); + }); + + for (const key of keys) { + newItem[key] = item[key]; + } + + return newItem; + } + + static normalizeCondition(condition) { + if (!condition) throw new Error("Expected condition but got falsy value"); + if (typeof condition === "string") { + return str => str.indexOf(condition) === 0; + } + if (typeof condition === "function") { + return condition; + } + if (condition instanceof RegExp) { + return condition.test.bind(condition); + } + if (Array.isArray(condition)) { + const items = condition.map(c => RuleSet.normalizeCondition(c)); + return orMatcher(items); + } + if (typeof condition !== "object") { + throw Error( + "Unexcepted " + + typeof condition + + " when condition was expected (" + + condition + + ")" + ); + } + + const matchers = []; + Object.keys(condition).forEach(key => { + const value = condition[key]; + switch (key) { + case "or": + case "include": + case "test": + if (value) matchers.push(RuleSet.normalizeCondition(value)); + break; + case "and": + if (value) { + const items = value.map(c => RuleSet.normalizeCondition(c)); + matchers.push(andMatcher(items)); + } + break; + case "not": + case "exclude": + if (value) { + const matcher = RuleSet.normalizeCondition(value); + matchers.push(notMatcher(matcher)); + } + break; + default: + throw new Error("Unexcepted property " + key + " in condition"); + } + }); + if (matchers.length === 0) { + throw new Error("Excepted condition but got " + condition); + } + if (matchers.length === 1) { + return matchers[0]; + } + return andMatcher(matchers); + } + + exec(data) { + const result = []; + this._run( + data, + { + rules: this.rules + }, + result + ); + return result; + } + + _run(data, rule, result) { + // test conditions + if (rule.resource && !data.resource) return false; + if (rule.realResource && !data.realResource) return false; + if (rule.resourceQuery && !data.resourceQuery) return false; + if (rule.compiler && !data.compiler) return false; + if (rule.issuer && !data.issuer) return false; + if (rule.resource && !rule.resource(data.resource)) return false; + if (rule.realResource && !rule.realResource(data.realResource)) + return false; + if (data.issuer && rule.issuer && !rule.issuer(data.issuer)) return false; + if ( + data.resourceQuery && + rule.resourceQuery && + !rule.resourceQuery(data.resourceQuery) + ) { + return false; + } + if (data.compiler && rule.compiler && !rule.compiler(data.compiler)) { + return false; + } + + // apply + const keys = Object.keys(rule).filter(key => { + return ![ + "resource", + "realResource", + "resourceQuery", + "compiler", + "issuer", + "rules", + "oneOf", + "use", + "enforce" + ].includes(key); + }); + for (const key of keys) { + result.push({ + type: key, + value: rule[key] + }); + } + + if (rule.use) { + const process = use => { + if (typeof use === "function") { + process(use(data)); + } else if (Array.isArray(use)) { + use.forEach(process); + } else { + result.push({ + type: "use", + value: use, + enforce: rule.enforce + }); + } + }; + process(rule.use); + } + + if (rule.rules) { + for (let i = 0; i < rule.rules.length; i++) { + this._run(data, rule.rules[i], result); + } + } + + if (rule.oneOf) { + for (let i = 0; i < rule.oneOf.length; i++) { + if (this._run(data, rule.oneOf[i], result)) break; + } + } + + return true; + } + + findOptionsByIdent(ident) { + const options = this.references[ident]; + if (!options) { + throw new Error("Can't find options with ident '" + ident + "'"); + } + return options; + } +}; diff --git a/node_modules/webpack/lib/SetVarMainTemplatePlugin.js b/node_modules/webpack/lib/SetVarMainTemplatePlugin.js index 67b3e744e..63db2821a 100644 --- a/node_modules/webpack/lib/SetVarMainTemplatePlugin.js +++ b/node_modules/webpack/lib/SetVarMainTemplatePlugin.js @@ -1,41 +1,69 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const ConcatSource = require("webpack-sources").ConcatSource;
-
-class SetVarMainTemplatePlugin {
- constructor(varExpression, copyObject) {
- this.varExpression = varExpression;
- this.copyObject = copyObject;
- }
-
- apply(compilation) {
- const mainTemplate = compilation.mainTemplate;
- compilation.templatesPlugin("render-with-entry", (source, chunk, hash) => {
- const varExpression = mainTemplate.applyPluginsWaterfall("asset-path", this.varExpression, {
- hash,
- chunk
- });
- if(this.copyObject) {
- return new ConcatSource(`(function(e, a) { for(var i in a) e[i] = a[i]; }(${varExpression}, `, source, "))");
- } else {
- const prefix = `${varExpression} =\n`;
- return new ConcatSource(prefix, source);
- }
- });
- mainTemplate.plugin("global-hash-paths", (paths) => {
- if(this.varExpression) paths.push(this.varExpression);
- return paths;
- });
- mainTemplate.plugin("hash", hash => {
- hash.update("set var");
- hash.update(`${this.varExpression}`);
- hash.update(`${this.copyObject}`);
- });
- }
-}
-
-module.exports = SetVarMainTemplatePlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const { ConcatSource } = require("webpack-sources"); + +/** @typedef {import("./Compilation")} Compilation */ + +class SetVarMainTemplatePlugin { + /** + * @param {string} varExpression the accessor where the library is exported + * @param {boolean} copyObject specify copying the exports + */ + constructor(varExpression, copyObject) { + /** @type {string} */ + this.varExpression = varExpression; + /** @type {boolean} */ + this.copyObject = copyObject; + } + + /** + * @param {Compilation} compilation the compilation instance + * @returns {void} + */ + apply(compilation) { + const { mainTemplate, chunkTemplate } = compilation; + + const onRenderWithEntry = (source, chunk, hash) => { + const varExpression = mainTemplate.getAssetPath(this.varExpression, { + hash, + chunk + }); + if (this.copyObject) { + return new ConcatSource( + `(function(e, a) { for(var i in a) e[i] = a[i]; }(${varExpression}, `, + source, + "))" + ); + } else { + const prefix = `${varExpression} =\n`; + return new ConcatSource(prefix, source); + } + }; + + for (const template of [mainTemplate, chunkTemplate]) { + template.hooks.renderWithEntry.tap( + "SetVarMainTemplatePlugin", + onRenderWithEntry + ); + } + + mainTemplate.hooks.globalHashPaths.tap( + "SetVarMainTemplatePlugin", + paths => { + if (this.varExpression) paths.push(this.varExpression); + return paths; + } + ); + mainTemplate.hooks.hash.tap("SetVarMainTemplatePlugin", hash => { + hash.update("set var"); + hash.update(`${this.varExpression}`); + hash.update(`${this.copyObject}`); + }); + } +} + +module.exports = SetVarMainTemplatePlugin; diff --git a/node_modules/webpack/lib/SingleEntryPlugin.js b/node_modules/webpack/lib/SingleEntryPlugin.js index aa5da3a0a..4a1703b1f 100644 --- a/node_modules/webpack/lib/SingleEntryPlugin.js +++ b/node_modules/webpack/lib/SingleEntryPlugin.js @@ -1,35 +1,63 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const SingleEntryDependency = require("./dependencies/SingleEntryDependency");
-
-class SingleEntryPlugin {
- constructor(context, entry, name) {
- this.context = context;
- this.entry = entry;
- this.name = name;
- }
-
- apply(compiler) {
- compiler.plugin("compilation", (compilation, params) => {
- const normalModuleFactory = params.normalModuleFactory;
-
- compilation.dependencyFactories.set(SingleEntryDependency, normalModuleFactory);
- });
-
- compiler.plugin("make", (compilation, callback) => {
- const dep = SingleEntryPlugin.createDependency(this.entry, this.name);
- compilation.addEntry(this.context, dep, this.name, callback);
- });
- }
-
- static createDependency(entry, name) {
- const dep = new SingleEntryDependency(entry);
- dep.loc = name;
- return dep;
- }
-}
-
-module.exports = SingleEntryPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const SingleEntryDependency = require("./dependencies/SingleEntryDependency"); + +/** @typedef {import("./Compiler")} Compiler */ + +class SingleEntryPlugin { + /** + * An entry plugin which will handle + * creation of the SingleEntryDependency + * + * @param {string} context context path + * @param {string} entry entry path + * @param {string} name entry key name + */ + constructor(context, entry, name) { + this.context = context; + this.entry = entry; + this.name = name; + } + + /** + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "SingleEntryPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + SingleEntryDependency, + normalModuleFactory + ); + } + ); + + compiler.hooks.make.tapAsync( + "SingleEntryPlugin", + (compilation, callback) => { + const { entry, name, context } = this; + + const dep = SingleEntryPlugin.createDependency(entry, name); + compilation.addEntry(context, dep, name, callback); + } + ); + } + + /** + * @param {string} entry entry request + * @param {string} name entry name + * @returns {SingleEntryDependency} the dependency + */ + static createDependency(entry, name) { + const dep = new SingleEntryDependency(entry); + dep.loc = { name }; + return dep; + } +} + +module.exports = SingleEntryPlugin; diff --git a/node_modules/webpack/lib/SizeFormatHelpers.js b/node_modules/webpack/lib/SizeFormatHelpers.js index 3b7732199..c4677f60b 100644 --- a/node_modules/webpack/lib/SizeFormatHelpers.js +++ b/node_modules/webpack/lib/SizeFormatHelpers.js @@ -1,18 +1,24 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Sean Larkin @thelarkinn
-*/
-"use strict";
-
-const SizeFormatHelpers = exports;
-
-SizeFormatHelpers.formatSize = size => {
- if(size <= 0) {
- return "0 bytes";
- }
-
- const abbreviations = ["bytes", "kB", "MB", "GB"];
- const index = Math.floor(Math.log(size) / Math.log(1000));
-
- return `${+(size / Math.pow(1000, index)).toPrecision(3)} ${abbreviations[index]}`;
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sean Larkin @thelarkinn +*/ +"use strict"; + +const SizeFormatHelpers = exports; + +SizeFormatHelpers.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 `${+(size / Math.pow(1024, index)).toPrecision(3)} ${ + abbreviations[index] + }`; +}; diff --git a/node_modules/webpack/lib/SourceMapDevToolModuleOptionsPlugin.js b/node_modules/webpack/lib/SourceMapDevToolModuleOptionsPlugin.js index 312ad43fe..e593ced7b 100644 --- a/node_modules/webpack/lib/SourceMapDevToolModuleOptionsPlugin.js +++ b/node_modules/webpack/lib/SourceMapDevToolModuleOptionsPlugin.js @@ -1,37 +1,49 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
-
-class SourceMapDevToolModuleOptionsPlugin {
- constructor(options) {
- this.options = options;
- }
-
- apply(compilation) {
- const options = this.options;
- if(options.module !== false) {
- compilation.plugin("build-module", module => {
- module.useSourceMap = true;
- });
- }
- if(options.lineToLine === true) {
- compilation.plugin("build-module", module => {
- module.lineToLine = true;
- });
- } else if(options.lineToLine) {
- compilation.plugin("build-module", module => {
- if(!module.resource) return;
- let resourcePath = module.resource;
- const idx = resourcePath.indexOf("?");
- if(idx >= 0) resourcePath = resourcePath.substr(0, idx);
- module.lineToLine = ModuleFilenameHelpers.matchObject(options.lineToLine, resourcePath);
- });
- }
- }
-}
-
-module.exports = SourceMapDevToolModuleOptionsPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const ModuleFilenameHelpers = require("./ModuleFilenameHelpers"); + +class SourceMapDevToolModuleOptionsPlugin { + constructor(options) { + this.options = options; + } + + apply(compilation) { + const options = this.options; + if (options.module !== false) { + compilation.hooks.buildModule.tap( + "SourceMapDevToolModuleOptionsPlugin", + module => { + module.useSourceMap = true; + } + ); + } + if (options.lineToLine === true) { + compilation.hooks.buildModule.tap( + "SourceMapDevToolModuleOptionsPlugin", + module => { + module.lineToLine = true; + } + ); + } else if (options.lineToLine) { + compilation.hooks.buildModule.tap( + "SourceMapDevToolModuleOptionsPlugin", + module => { + if (!module.resource) return; + let resourcePath = module.resource; + const idx = resourcePath.indexOf("?"); + if (idx >= 0) resourcePath = resourcePath.substr(0, idx); + module.lineToLine = ModuleFilenameHelpers.matchObject( + options.lineToLine, + resourcePath + ); + } + ); + } + } +} + +module.exports = SourceMapDevToolModuleOptionsPlugin; diff --git a/node_modules/webpack/lib/SourceMapDevToolPlugin.js b/node_modules/webpack/lib/SourceMapDevToolPlugin.js index e63f34afb..315a9c22c 100644 --- a/node_modules/webpack/lib/SourceMapDevToolPlugin.js +++ b/node_modules/webpack/lib/SourceMapDevToolPlugin.js @@ -1,209 +1,301 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const path = require("path");
-const crypto = require("crypto");
-const RequestShortener = require("./RequestShortener");
-const ConcatSource = require("webpack-sources").ConcatSource;
-const RawSource = require("webpack-sources").RawSource;
-const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
-const SourceMapDevToolModuleOptionsPlugin = require("./SourceMapDevToolModuleOptionsPlugin");
-
-const basename = (name) => {
- if(name.indexOf("/") < 0) return name;
- return name.substr(name.lastIndexOf("/") + 1);
-};
-
-function getTaskForFile(file, chunk, options, compilation) {
- const asset = compilation.assets[file];
- if(asset.__SourceMapDevToolFile === file && asset.__SourceMapDevToolData) {
- const data = asset.__SourceMapDevToolData;
- for(const cachedFile in data) {
- compilation.assets[cachedFile] = data[cachedFile];
- if(cachedFile !== file)
- chunk.files.push(cachedFile);
- }
- return;
- }
- let source, sourceMap;
- if(asset.sourceAndMap) {
- const sourceAndMap = asset.sourceAndMap(options);
- sourceMap = sourceAndMap.map;
- source = sourceAndMap.source;
- } else {
- sourceMap = asset.map(options);
- source = asset.source();
- }
- if(sourceMap) {
- return {
- chunk,
- file,
- asset,
- source,
- sourceMap,
- modules: undefined
- };
- }
-}
-
-class SourceMapDevToolPlugin {
- constructor(options) {
- if(arguments.length > 1)
- throw new Error("SourceMapDevToolPlugin only takes one argument (pass an options object)");
- // TODO: remove in webpack 3
- if(typeof options === "string") {
- options = {
- sourceMapFilename: options
- };
- }
- if(!options) options = {};
- this.sourceMapFilename = options.filename;
- this.sourceMappingURLComment = options.append === false ? false : options.append || "\n//# sourceMappingURL=[url]";
- this.moduleFilenameTemplate = options.moduleFilenameTemplate || "webpack:///[resourcePath]";
- this.fallbackModuleFilenameTemplate = options.fallbackModuleFilenameTemplate || "webpack:///[resourcePath]?[hash]";
- this.options = options;
- }
-
- apply(compiler) {
- const sourceMapFilename = this.sourceMapFilename;
- const sourceMappingURLComment = this.sourceMappingURLComment;
- const moduleFilenameTemplate = this.moduleFilenameTemplate;
- const fallbackModuleFilenameTemplate = this.fallbackModuleFilenameTemplate;
- const requestShortener = new RequestShortener(compiler.context);
- const options = this.options;
- options.test = options.test || /\.(js|css)($|\?)/i;
-
- const matchObject = ModuleFilenameHelpers.matchObject.bind(undefined, options);
-
- compiler.plugin("compilation", compilation => {
- new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation);
-
- compilation.plugin("after-optimize-chunk-assets", function(chunks) {
- const moduleToSourceNameMapping = new Map();
- const tasks = [];
-
- chunks.forEach(function(chunk) {
- chunk.files.forEach(file => {
- if(matchObject(file)) {
- const task = getTaskForFile(file, chunk, options, compilation);
-
- if(task) {
- const modules = task.sourceMap.sources.map(source => {
- const module = compilation.findModule(source);
- return module || source;
- });
-
- for(let idx = 0; idx < modules.length; idx++) {
- const module = modules[idx];
- if(!moduleToSourceNameMapping.get(module)) {
- moduleToSourceNameMapping.set(module, ModuleFilenameHelpers.createFilename(module, moduleFilenameTemplate, requestShortener));
- }
- }
-
- task.modules = modules;
-
- tasks.push(task);
- }
- }
- });
- });
-
- const usedNamesSet = new Set(moduleToSourceNameMapping.values());
- const conflictDetectionSet = new Set();
-
- // all modules in defined order (longest identifier first)
- const allModules = Array.from(moduleToSourceNameMapping.keys()).sort((a, b) => {
- const ai = typeof a === "string" ? a : a.identifier();
- const bi = typeof b === "string" ? b : b.identifier();
- return ai.length - bi.length;
- });
-
- // find modules with conflicting source names
- for(let idx = 0; idx < allModules.length; idx++) {
- const module = allModules[idx];
- let sourceName = moduleToSourceNameMapping.get(module);
- let hasName = conflictDetectionSet.has(sourceName);
- if(!hasName) {
- conflictDetectionSet.add(sourceName);
- continue;
- }
-
- // try the fallback name first
- sourceName = ModuleFilenameHelpers.createFilename(module, fallbackModuleFilenameTemplate, requestShortener);
- hasName = usedNamesSet.has(sourceName);
- if(!hasName) {
- moduleToSourceNameMapping.set(module, sourceName);
- usedNamesSet.add(sourceName);
- continue;
- }
-
- // elsewise just append stars until we have a valid name
- while(hasName) {
- sourceName += "*";
- hasName = usedNamesSet.has(sourceName);
- }
- moduleToSourceNameMapping.set(module, sourceName);
- usedNamesSet.add(sourceName);
- }
- tasks.forEach(function(task) {
- const chunk = task.chunk;
- const file = task.file;
- const asset = task.asset;
- const sourceMap = task.sourceMap;
- const source = task.source;
- const modules = task.modules;
- const moduleFilenames = modules.map(m => moduleToSourceNameMapping.get(m));
- sourceMap.sources = moduleFilenames;
- if(sourceMap.sourcesContent && !options.noSources) {
- sourceMap.sourcesContent = sourceMap.sourcesContent.map((content, i) => typeof content === "string" ? `${content}\n\n\n${ModuleFilenameHelpers.createFooter(modules[i], requestShortener)}` : null);
- } else {
- sourceMap.sourcesContent = undefined;
- }
- sourceMap.sourceRoot = options.sourceRoot || "";
- sourceMap.file = file;
- asset.__SourceMapDevToolFile = file;
- asset.__SourceMapDevToolData = {};
- let currentSourceMappingURLComment = sourceMappingURLComment;
- if(currentSourceMappingURLComment !== false && /\.css($|\?)/i.test(file)) {
- currentSourceMappingURLComment = currentSourceMappingURLComment.replace(/^\n\/\/(.*)$/, "\n/*$1*/");
- }
- const sourceMapString = JSON.stringify(sourceMap);
- if(sourceMapFilename) {
- let filename = file;
- let query = "";
- const idx = filename.indexOf("?");
- if(idx >= 0) {
- query = filename.substr(idx);
- filename = filename.substr(0, idx);
- }
- let sourceMapFile = compilation.getPath(sourceMapFilename, {
- chunk,
- filename: options.fileContext ? path.relative(options.fileContext, filename) : filename,
- query,
- basename: basename(filename)
- });
- if(sourceMapFile.indexOf("[contenthash]") !== -1) {
- sourceMapFile = sourceMapFile.replace(/\[contenthash\]/g, crypto.createHash("md5").update(sourceMapString).digest("hex"));
- }
- const sourceMapUrl = options.publicPath ? options.publicPath + sourceMapFile.replace(/\\/g, "/") : path.relative(path.dirname(file), sourceMapFile).replace(/\\/g, "/");
- if(currentSourceMappingURLComment !== false) {
- asset.__SourceMapDevToolData[file] = compilation.assets[file] = new ConcatSource(new RawSource(source), currentSourceMappingURLComment.replace(/\[url\]/g, sourceMapUrl));
- }
- asset.__SourceMapDevToolData[sourceMapFile] = compilation.assets[sourceMapFile] = new RawSource(sourceMapString);
- chunk.files.push(sourceMapFile);
- } else {
- asset.__SourceMapDevToolData[file] = compilation.assets[file] = new ConcatSource(new RawSource(source), currentSourceMappingURLComment
- .replace(/\[map\]/g, () => sourceMapString)
- .replace(/\[url\]/g, () => `data:application/json;charset=utf-8;base64,${new Buffer(sourceMapString, "utf-8").toString("base64")}`) // eslint-disable-line
- );
- }
- });
- });
- });
- }
-}
-
-module.exports = SourceMapDevToolPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const path = require("path"); +const { ConcatSource, RawSource } = require("webpack-sources"); +const ModuleFilenameHelpers = require("./ModuleFilenameHelpers"); +const SourceMapDevToolModuleOptionsPlugin = require("./SourceMapDevToolModuleOptionsPlugin"); +const createHash = require("./util/createHash"); + +const validateOptions = require("schema-utils"); +const schema = require("../schemas/plugins/SourceMapDevToolPlugin.json"); + +const basename = name => { + if (!name.includes("/")) return name; + return name.substr(name.lastIndexOf("/") + 1); +}; + +const assetsCache = new WeakMap(); + +const getTaskForFile = (file, chunk, options, compilation) => { + const asset = compilation.assets[file]; + const cache = assetsCache.get(asset); + if (cache && cache.file === file) { + for (const cachedFile in cache.assets) { + compilation.assets[cachedFile] = cache.assets[cachedFile]; + if (cachedFile !== file) chunk.files.push(cachedFile); + } + return; + } + let source, sourceMap; + if (asset.sourceAndMap) { + const sourceAndMap = asset.sourceAndMap(options); + sourceMap = sourceAndMap.map; + source = sourceAndMap.source; + } else { + sourceMap = asset.map(options); + source = asset.source(); + } + if (sourceMap) { + return { + chunk, + file, + asset, + source, + sourceMap, + modules: undefined + }; + } +}; + +class SourceMapDevToolPlugin { + constructor(options) { + if (arguments.length > 1) { + throw new Error( + "SourceMapDevToolPlugin only takes one argument (pass an options object)" + ); + } + + validateOptions(schema, options || {}, "SourceMap DevTool Plugin"); + + if (!options) options = {}; + this.sourceMapFilename = options.filename; + this.sourceMappingURLComment = + options.append === false + ? false + : options.append || "\n//# sourceMappingURL=[url]"; + this.moduleFilenameTemplate = + options.moduleFilenameTemplate || "webpack://[namespace]/[resourcePath]"; + this.fallbackModuleFilenameTemplate = + options.fallbackModuleFilenameTemplate || + "webpack://[namespace]/[resourcePath]?[hash]"; + this.namespace = options.namespace || ""; + this.options = options; + } + + apply(compiler) { + const sourceMapFilename = this.sourceMapFilename; + const sourceMappingURLComment = this.sourceMappingURLComment; + const moduleFilenameTemplate = this.moduleFilenameTemplate; + const namespace = this.namespace; + const fallbackModuleFilenameTemplate = this.fallbackModuleFilenameTemplate; + const requestShortener = compiler.requestShortener; + const options = this.options; + options.test = options.test || /\.(m?js|css)($|\?)/i; + + const matchObject = ModuleFilenameHelpers.matchObject.bind( + undefined, + options + ); + + compiler.hooks.compilation.tap("SourceMapDevToolPlugin", compilation => { + new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation); + + compilation.hooks.afterOptimizeChunkAssets.tap( + { + name: "SourceMapDevToolPlugin", + context: true + }, + (context, chunks) => { + const moduleToSourceNameMapping = new Map(); + const reportProgress = + context && context.reportProgress + ? context.reportProgress + : () => {}; + + const files = []; + for (const chunk of chunks) { + for (const file of chunk.files) { + if (matchObject(file)) { + files.push({ + file, + chunk + }); + } + } + } + + reportProgress(0.0); + const tasks = []; + files.forEach(({ file, chunk }, idx) => { + reportProgress( + (0.5 * idx) / files.length, + file, + "generate SourceMap" + ); + const task = getTaskForFile(file, chunk, options, compilation); + + if (task) { + const modules = task.sourceMap.sources.map(source => { + const module = compilation.findModule(source); + return module || source; + }); + + for (let idx = 0; idx < modules.length; idx++) { + const module = modules[idx]; + if (!moduleToSourceNameMapping.get(module)) { + moduleToSourceNameMapping.set( + module, + ModuleFilenameHelpers.createFilename( + module, + { + moduleFilenameTemplate: moduleFilenameTemplate, + namespace: namespace + }, + requestShortener + ) + ); + } + } + + task.modules = modules; + + tasks.push(task); + } + }); + + reportProgress(0.5, "resolve sources"); + const usedNamesSet = new Set(moduleToSourceNameMapping.values()); + const conflictDetectionSet = new Set(); + + // all modules in defined order (longest identifier first) + const allModules = Array.from(moduleToSourceNameMapping.keys()).sort( + (a, b) => { + const ai = typeof a === "string" ? a : a.identifier(); + const bi = typeof b === "string" ? b : b.identifier(); + return ai.length - bi.length; + } + ); + + // find modules with conflicting source names + for (let idx = 0; idx < allModules.length; idx++) { + const module = allModules[idx]; + let sourceName = moduleToSourceNameMapping.get(module); + let hasName = conflictDetectionSet.has(sourceName); + if (!hasName) { + conflictDetectionSet.add(sourceName); + continue; + } + + // try the fallback name first + sourceName = ModuleFilenameHelpers.createFilename( + module, + { + moduleFilenameTemplate: fallbackModuleFilenameTemplate, + namespace: namespace + }, + requestShortener + ); + hasName = usedNamesSet.has(sourceName); + if (!hasName) { + moduleToSourceNameMapping.set(module, sourceName); + usedNamesSet.add(sourceName); + continue; + } + + // elsewise just append stars until we have a valid name + while (hasName) { + sourceName += "*"; + hasName = usedNamesSet.has(sourceName); + } + moduleToSourceNameMapping.set(module, sourceName); + usedNamesSet.add(sourceName); + } + tasks.forEach((task, index) => { + reportProgress( + 0.5 + (0.5 * index) / tasks.length, + task.file, + "attach SourceMap" + ); + const assets = Object.create(null); + const chunk = task.chunk; + const file = task.file; + const asset = task.asset; + const sourceMap = task.sourceMap; + const source = task.source; + const modules = task.modules; + const moduleFilenames = modules.map(m => + moduleToSourceNameMapping.get(m) + ); + sourceMap.sources = moduleFilenames; + if (options.noSources) { + sourceMap.sourcesContent = undefined; + } + sourceMap.sourceRoot = options.sourceRoot || ""; + sourceMap.file = file; + assetsCache.set(asset, { file, assets }); + let currentSourceMappingURLComment = sourceMappingURLComment; + if ( + currentSourceMappingURLComment !== false && + /\.css($|\?)/i.test(file) + ) { + currentSourceMappingURLComment = currentSourceMappingURLComment.replace( + /^\n\/\/(.*)$/, + "\n/*$1*/" + ); + } + const sourceMapString = JSON.stringify(sourceMap); + if (sourceMapFilename) { + let filename = file; + let query = ""; + const idx = filename.indexOf("?"); + if (idx >= 0) { + query = filename.substr(idx); + filename = filename.substr(0, idx); + } + let sourceMapFile = compilation.getPath(sourceMapFilename, { + chunk, + filename: options.fileContext + ? path.relative(options.fileContext, filename) + : filename, + query, + basename: basename(filename), + contentHash: createHash("md4") + .update(sourceMapString) + .digest("hex") + }); + const sourceMapUrl = options.publicPath + ? options.publicPath + sourceMapFile.replace(/\\/g, "/") + : path + .relative(path.dirname(file), sourceMapFile) + .replace(/\\/g, "/"); + if (currentSourceMappingURLComment !== false) { + assets[file] = compilation.assets[file] = new ConcatSource( + new RawSource(source), + currentSourceMappingURLComment.replace( + /\[url\]/g, + sourceMapUrl + ) + ); + } + assets[sourceMapFile] = compilation.assets[ + sourceMapFile + ] = new RawSource(sourceMapString); + chunk.files.push(sourceMapFile); + } else { + assets[file] = compilation.assets[file] = new ConcatSource( + new RawSource(source), + currentSourceMappingURLComment + .replace(/\[map\]/g, () => sourceMapString) + .replace( + /\[url\]/g, + () => + `data:application/json;charset=utf-8;base64,${Buffer.from( + sourceMapString, + "utf-8" + ).toString("base64")}` + ) + ); + } + }); + reportProgress(1.0); + } + ); + }); + } +} + +module.exports = SourceMapDevToolPlugin; diff --git a/node_modules/webpack/lib/Stats.js b/node_modules/webpack/lib/Stats.js index 6aa3d1ac9..fd7902bee 100644 --- a/node_modules/webpack/lib/Stats.js +++ b/node_modules/webpack/lib/Stats.js @@ -1,983 +1,1435 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const RequestShortener = require("./RequestShortener");
-const SizeFormatHelpers = require("./SizeFormatHelpers");
-const formatLocation = require("./formatLocation");
-const identifierUtils = require("./util/identifier");
-
-const optionsOrFallback = function() {
- let optionValues = [];
- optionValues.push.apply(optionValues, arguments);
- return optionValues.find(optionValue => typeof optionValue !== "undefined");
-};
-
-class Stats {
- constructor(compilation) {
- this.compilation = compilation;
- this.hash = compilation.hash;
- }
-
- static filterWarnings(warnings, warningsFilter) {
- // we dont have anything to filter so all warnings can be shown
- if(!warningsFilter) {
- return warnings;
- }
-
- // create a chain of filters
- // if they return "true" a warning should be surpressed
- const normalizedWarningsFilters = [].concat(warningsFilter).map(filter => {
- if(typeof filter === "string") {
- return warning => warning.indexOf(filter) > -1;
- }
-
- if(filter instanceof RegExp) {
- return warning => filter.test(warning);
- }
-
- if(typeof filter === "function") {
- return filter;
- }
-
- throw new Error(`Can only filter warnings with Strings or RegExps. (Given: ${filter})`);
- });
- return warnings.filter(warning => {
- return !normalizedWarningsFilters.some(check => check(warning));
- });
- }
-
- hasWarnings() {
- return this.compilation.warnings.length > 0;
- }
-
- hasErrors() {
- return this.compilation.errors.length > 0;
- }
-
- // remove a prefixed "!" that can be specified to reverse sort order
- normalizeFieldKey(field) {
- if(field[0] === "!") {
- return field.substr(1);
- }
- return field;
- }
-
- // if a field is prefixed by a "!" reverse sort order
- sortOrderRegular(field) {
- if(field[0] === "!") {
- return false;
- }
- return true;
- }
-
- toJson(options, forToString) {
- if(typeof options === "boolean" || typeof options === "string") {
- options = Stats.presetToOptions(options);
- } else if(!options) {
- options = {};
- }
-
- const optionOrLocalFallback = (v, def) =>
- typeof v !== "undefined" ? v :
- typeof options.all !== "undefined" ? options.all : def;
-
- const testAgainstGivenOption = (item) => {
- if(typeof item === "string") {
- const regExp = new RegExp(`[\\\\/]${item.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&")}([\\\\/]|$|!|\\?)`); // eslint-disable-line no-useless-escape
- return ident => regExp.test(ident);
- }
- if(item && typeof item === "object" && typeof item.test === "function")
- return ident => item.test(ident);
- if(typeof item === "function")
- return item;
- };
-
- const compilation = this.compilation;
- const context = optionsOrFallback(options.context, process.cwd());
- const requestShortener = new RequestShortener(context);
- const showPerformance = optionOrLocalFallback(options.performance, true);
- const showHash = optionOrLocalFallback(options.hash, true);
- const showEnv = optionOrLocalFallback(options.env, false);
- const showVersion = optionOrLocalFallback(options.version, true);
- const showTimings = optionOrLocalFallback(options.timings, true);
- const showAssets = optionOrLocalFallback(options.assets, true);
- const showEntrypoints = optionOrLocalFallback(options.entrypoints, !forToString);
- const showChunks = optionOrLocalFallback(options.chunks, !forToString);
- const showChunkModules = optionOrLocalFallback(options.chunkModules, true);
- const showChunkOrigins = optionOrLocalFallback(options.chunkOrigins, !forToString);
- const showModules = optionOrLocalFallback(options.modules, true);
- const showDepth = optionOrLocalFallback(options.depth, !forToString);
- const showCachedModules = optionOrLocalFallback(options.cached, true);
- const showCachedAssets = optionOrLocalFallback(options.cachedAssets, true);
- const showReasons = optionOrLocalFallback(options.reasons, !forToString);
- const showUsedExports = optionOrLocalFallback(options.usedExports, !forToString);
- const showProvidedExports = optionOrLocalFallback(options.providedExports, !forToString);
- const showOptimizationBailout = optionOrLocalFallback(options.optimizationBailout, !forToString);
- const showChildren = optionOrLocalFallback(options.children, true);
- const showSource = optionOrLocalFallback(options.source, !forToString);
- const showModuleTrace = optionOrLocalFallback(options.moduleTrace, true);
- const showErrors = optionOrLocalFallback(options.errors, true);
- const showErrorDetails = optionOrLocalFallback(options.errorDetails, !forToString);
- const showWarnings = optionOrLocalFallback(options.warnings, true);
- const warningsFilter = optionsOrFallback(options.warningsFilter, null);
- const showPublicPath = optionOrLocalFallback(options.publicPath, !forToString);
- const excludeModules = [].concat(optionsOrFallback(options.excludeModules, options.exclude, [])).map(testAgainstGivenOption);
- const excludeAssets = [].concat(optionsOrFallback(options.excludeAssets, [])).map(testAgainstGivenOption);
- const maxModules = optionsOrFallback(options.maxModules, forToString ? 15 : Infinity);
- const sortModules = optionsOrFallback(options.modulesSort, "id");
- const sortChunks = optionsOrFallback(options.chunksSort, "id");
- const sortAssets = optionsOrFallback(options.assetsSort, "");
-
- if(!showCachedModules) {
- excludeModules.push((ident, module) => !module.built);
- }
-
- const createModuleFilter = () => {
- let i = 0;
- return module => {
- if(excludeModules.length > 0) {
- const ident = requestShortener.shorten(module.resource);
- const excluded = excludeModules.some(fn => fn(ident, module));
- if(excluded)
- return false;
- }
- return i++ < maxModules;
- };
- };
-
- const createAssetFilter = () => {
- return asset => {
- if(excludeAssets.length > 0) {
- const ident = asset.name;
- const excluded = excludeAssets.some(fn => fn(ident, asset));
- if(excluded)
- return false;
- }
- return showCachedAssets || asset.emitted;
- };
- };
-
- const sortByFieldAndOrder = (fieldKey, a, b) => {
- if(a[fieldKey] === null && b[fieldKey] === null) return 0;
- if(a[fieldKey] === null) return 1;
- if(b[fieldKey] === null) return -1;
- if(a[fieldKey] === b[fieldKey]) return 0;
- return a[fieldKey] < b[fieldKey] ? -1 : 1;
- };
-
- const sortByField = (field) => (a, b) => {
- if(!field) {
- return 0;
- }
-
- const fieldKey = this.normalizeFieldKey(field);
-
- // if a field is prefixed with a "!" the sort is reversed!
- const sortIsRegular = this.sortOrderRegular(field);
-
- return sortByFieldAndOrder(fieldKey, sortIsRegular ? a : b, sortIsRegular ? b : a);
- };
-
- const formatError = (e) => {
- let text = "";
- if(typeof e === "string")
- e = {
- message: e
- };
- if(e.chunk) {
- text += `chunk ${e.chunk.name || e.chunk.id}${e.chunk.hasRuntime() ? " [entry]" : e.chunk.isInitial() ? " [initial]" : ""}\n`;
- }
- if(e.file) {
- text += `${e.file}\n`;
- }
- if(e.module && e.module.readableIdentifier && typeof e.module.readableIdentifier === "function") {
- text += `${e.module.readableIdentifier(requestShortener)}\n`;
- }
- text += e.message;
- if(showErrorDetails && e.details) text += `\n${e.details}`;
- if(showErrorDetails && e.missing) text += e.missing.map(item => `\n[${item}]`).join("");
- if(showModuleTrace && e.origin) {
- text += `\n @ ${e.origin.readableIdentifier(requestShortener)}`;
- if(typeof e.originLoc === "object") {
- const locInfo = formatLocation(e.originLoc);
- if(locInfo)
- text += ` ${locInfo}`;
- }
- if(e.dependencies) {
- e.dependencies.forEach(dep => {
- if(!dep.loc) return;
- if(typeof dep.loc === "string") return;
- const locInfo = formatLocation(dep.loc);
- if(!locInfo) return;
- text += ` ${locInfo}`;
- });
- }
- let current = e.origin;
- while(current.issuer) {
- current = current.issuer;
- text += `\n @ ${current.readableIdentifier(requestShortener)}`;
- }
- }
- return text;
- };
-
- const obj = {
- errors: compilation.errors.map(formatError),
- warnings: Stats.filterWarnings(compilation.warnings.map(formatError), warningsFilter)
- };
-
- //We just hint other renderers since actually omitting
- //errors/warnings from the JSON would be kind of weird.
- Object.defineProperty(obj, "_showWarnings", {
- value: showWarnings,
- enumerable: false
- });
- Object.defineProperty(obj, "_showErrors", {
- value: showErrors,
- enumerable: false
- });
-
- if(showVersion) {
- obj.version = require("../package.json").version;
- }
-
- if(showHash) obj.hash = this.hash;
- if(showTimings && this.startTime && this.endTime) {
- obj.time = this.endTime - this.startTime;
- }
-
- if(showEnv && options._env) {
- obj.env = options._env;
- }
-
- if(compilation.needAdditionalPass) {
- obj.needAdditionalPass = true;
- }
- if(showPublicPath) {
- obj.publicPath = this.compilation.mainTemplate.getPublicPath({
- hash: this.compilation.hash
- });
- }
- if(showAssets) {
- const assetsByFile = {};
- const compilationAssets = Object.keys(compilation.assets);
- obj.assetsByChunkName = {};
- obj.assets = compilationAssets.map(asset => {
- const obj = {
- name: asset,
- size: compilation.assets[asset].size(),
- chunks: [],
- chunkNames: [],
- emitted: compilation.assets[asset].emitted
- };
-
- if(showPerformance) {
- obj.isOverSizeLimit = compilation.assets[asset].isOverSizeLimit;
- }
-
- assetsByFile[asset] = obj;
- return obj;
- }).filter(createAssetFilter());
- obj.filteredAssets = compilationAssets.length - obj.assets.length;
-
- compilation.chunks.forEach(chunk => {
- chunk.files.forEach(asset => {
- if(assetsByFile[asset]) {
- chunk.ids.forEach(id => {
- assetsByFile[asset].chunks.push(id);
- });
- if(chunk.name) {
- assetsByFile[asset].chunkNames.push(chunk.name);
- if(obj.assetsByChunkName[chunk.name])
- obj.assetsByChunkName[chunk.name] = [].concat(obj.assetsByChunkName[chunk.name]).concat([asset]);
- else
- obj.assetsByChunkName[chunk.name] = asset;
- }
- }
- });
- });
- obj.assets.sort(sortByField(sortAssets));
- }
-
- if(showEntrypoints) {
- obj.entrypoints = {};
- Object.keys(compilation.entrypoints).forEach(name => {
- const ep = compilation.entrypoints[name];
- obj.entrypoints[name] = {
- chunks: ep.chunks.map(c => c.id),
- assets: ep.chunks.reduce((array, c) => array.concat(c.files || []), [])
- };
- if(showPerformance) {
- obj.entrypoints[name].isOverSizeLimit = ep.isOverSizeLimit;
- }
- });
- }
-
- function fnModule(module) {
- const obj = {
- id: module.id,
- identifier: module.identifier(),
- name: module.readableIdentifier(requestShortener),
- index: module.index,
- index2: module.index2,
- size: module.size(),
- cacheable: !!module.cacheable,
- built: !!module.built,
- optional: !!module.optional,
- prefetched: !!module.prefetched,
- chunks: module.mapChunks(chunk => chunk.id),
- assets: Object.keys(module.assets || {}),
- issuer: module.issuer && module.issuer.identifier(),
- issuerId: module.issuer && module.issuer.id,
- issuerName: module.issuer && module.issuer.readableIdentifier(requestShortener),
- profile: module.profile,
- failed: !!module.error,
- errors: module.errors && module.dependenciesErrors && (module.errors.length + module.dependenciesErrors.length),
- warnings: module.errors && module.dependenciesErrors && (module.warnings.length + module.dependenciesWarnings.length)
- };
- if(showReasons) {
- obj.reasons = module.reasons.filter(reason => reason.dependency && reason.module).map(reason => {
- const obj = {
- moduleId: reason.module.id,
- moduleIdentifier: reason.module.identifier(),
- module: reason.module.readableIdentifier(requestShortener),
- moduleName: reason.module.readableIdentifier(requestShortener),
- type: reason.dependency.type,
- userRequest: reason.dependency.userRequest
- };
- const locInfo = formatLocation(reason.dependency.loc);
- if(locInfo) obj.loc = locInfo;
- return obj;
- }).sort((a, b) => a.moduleId - b.moduleId);
- }
- if(showUsedExports) {
- obj.usedExports = module.used ? module.usedExports : false;
- }
- if(showProvidedExports) {
- obj.providedExports = Array.isArray(module.providedExports) ? module.providedExports : null;
- }
- if(showOptimizationBailout) {
- obj.optimizationBailout = module.optimizationBailout.map(item => {
- if(typeof item === "function") return item(requestShortener);
- return item;
- });
- }
- if(showDepth) {
- obj.depth = module.depth;
- }
- if(showSource && module._source) {
- obj.source = module._source.source();
- }
- return obj;
- }
- if(showChunks) {
- obj.chunks = compilation.chunks.map(chunk => {
- const obj = {
- id: chunk.id,
- rendered: chunk.rendered,
- initial: chunk.isInitial(),
- entry: chunk.hasRuntime(),
- recorded: chunk.recorded,
- extraAsync: !!chunk.extraAsync,
- size: chunk.mapModules(m => m.size()).reduce((size, moduleSize) => size + moduleSize, 0),
- names: chunk.name ? [chunk.name] : [],
- files: chunk.files.slice(),
- hash: chunk.renderedHash,
- parents: chunk.parents.map(c => c.id)
- };
- if(showChunkModules) {
- obj.modules = chunk
- .getModules()
- .sort(sortByField("depth"))
- .filter(createModuleFilter())
- .map(fnModule);
- obj.filteredModules = chunk.getNumberOfModules() - obj.modules.length;
- obj.modules.sort(sortByField(sortModules));
- }
- if(showChunkOrigins) {
- obj.origins = chunk.origins.map(origin => ({
- moduleId: origin.module ? origin.module.id : undefined,
- module: origin.module ? origin.module.identifier() : "",
- moduleIdentifier: origin.module ? origin.module.identifier() : "",
- moduleName: origin.module ? origin.module.readableIdentifier(requestShortener) : "",
- loc: formatLocation(origin.loc),
- name: origin.name,
- reasons: origin.reasons || []
- }));
- }
- return obj;
- });
- obj.chunks.sort(sortByField(sortChunks));
- }
- if(showModules) {
- obj.modules = compilation.modules
- .slice()
- .sort(sortByField("depth"))
- .filter(createModuleFilter())
- .map(fnModule);
- obj.filteredModules = compilation.modules.length - obj.modules.length;
- obj.modules.sort(sortByField(sortModules));
- }
- if(showChildren) {
- obj.children = compilation.children.map((child, idx) => {
- const childOptions = Stats.getChildOptions(options, idx);
- const obj = new Stats(child).toJson(childOptions, forToString);
- delete obj.hash;
- delete obj.version;
- if(child.name)
- obj.name = identifierUtils.makePathsRelative(context, child.name, compilation.cache);
- return obj;
- });
- }
-
- return obj;
- }
-
- toString(options) {
- if(typeof options === "boolean" || typeof options === "string") {
- options = Stats.presetToOptions(options);
- } else if(!options) {
- options = {};
- }
-
- const useColors = optionsOrFallback(options.colors, false);
-
- const obj = this.toJson(options, true);
-
- return Stats.jsonToString(obj, useColors);
- }
-
- static jsonToString(obj, useColors) {
- const buf = [];
-
- const defaultColors = {
- bold: "\u001b[1m",
- yellow: "\u001b[1m\u001b[33m",
- red: "\u001b[1m\u001b[31m",
- green: "\u001b[1m\u001b[32m",
- cyan: "\u001b[1m\u001b[36m",
- magenta: "\u001b[1m\u001b[35m"
- };
-
- const colors = Object.keys(defaultColors).reduce((obj, color) => {
- obj[color] = str => {
- if(useColors) {
- buf.push(
- (useColors === true || useColors[color] === undefined) ?
- defaultColors[color] : useColors[color]
- );
- }
- buf.push(str);
- if(useColors) {
- buf.push("\u001b[39m\u001b[22m");
- }
- };
- return obj;
- }, {
- normal: (str) => buf.push(str)
- });
-
- const coloredTime = (time) => {
- let times = [800, 400, 200, 100];
- if(obj.time) {
- times = [obj.time / 2, obj.time / 4, obj.time / 8, obj.time / 16];
- }
- if(time < times[3])
- colors.normal(`${time}ms`);
- else if(time < times[2])
- colors.bold(`${time}ms`);
- else if(time < times[1])
- colors.green(`${time}ms`);
- else if(time < times[0])
- colors.yellow(`${time}ms`);
- else
- colors.red(`${time}ms`);
- };
-
- const newline = () => buf.push("\n");
-
- const getText = (arr, row, col) => {
- return arr[row][col].value;
- };
-
- const table = (array, align, splitter) => {
- const rows = array.length;
- const cols = array[0].length;
- const colSizes = new Array(cols);
- for(let col = 0; col < cols; col++)
- colSizes[col] = 0;
- for(let row = 0; row < rows; row++) {
- for(let col = 0; col < cols; col++) {
- const value = `${getText(array, row, col)}`;
- if(value.length > colSizes[col]) {
- colSizes[col] = value.length;
- }
- }
- }
- for(let row = 0; row < rows; row++) {
- for(let col = 0; col < cols; col++) {
- const format = array[row][col].color;
- const value = `${getText(array, row, col)}`;
- let l = value.length;
- if(align[col] === "l")
- format(value);
- for(; l < colSizes[col] && col !== cols - 1; l++)
- colors.normal(" ");
- if(align[col] === "r")
- format(value);
- if(col + 1 < cols && colSizes[col] !== 0)
- colors.normal(splitter || " ");
- }
- newline();
- }
- };
-
- const getAssetColor = (asset, defaultColor) => {
- if(asset.isOverSizeLimit) {
- return colors.yellow;
- }
-
- return defaultColor;
- };
-
- if(obj.hash) {
- colors.normal("Hash: ");
- colors.bold(obj.hash);
- newline();
- }
- if(obj.version) {
- colors.normal("Version: webpack ");
- colors.bold(obj.version);
- newline();
- }
- if(typeof obj.time === "number") {
- colors.normal("Time: ");
- colors.bold(obj.time);
- colors.normal("ms");
- newline();
- }
- if(obj.env) {
- colors.normal("Environment (--env): ");
- colors.bold(JSON.stringify(obj.env, null, 2));
- newline();
- }
- if(obj.publicPath) {
- colors.normal("PublicPath: ");
- colors.bold(obj.publicPath);
- newline();
- }
-
- if(obj.assets && obj.assets.length > 0) {
- const t = [
- [{
- value: "Asset",
- color: colors.bold
- }, {
- value: "Size",
- color: colors.bold
- }, {
- value: "Chunks",
- color: colors.bold
- }, {
- value: "",
- color: colors.bold
- }, {
- value: "",
- color: colors.bold
- }, {
- value: "Chunk Names",
- color: colors.bold
- }]
- ];
- obj.assets.forEach(asset => {
- t.push([{
- value: asset.name,
- color: getAssetColor(asset, colors.green)
- }, {
- value: SizeFormatHelpers.formatSize(asset.size),
- color: getAssetColor(asset, colors.normal)
- }, {
- value: asset.chunks.join(", "),
- color: colors.bold
- }, {
- value: asset.emitted ? "[emitted]" : "",
- color: colors.green
- }, {
- value: asset.isOverSizeLimit ? "[big]" : "",
- color: getAssetColor(asset, colors.normal)
- }, {
- value: asset.chunkNames.join(", "),
- color: colors.normal
- }]);
- });
- table(t, "rrrlll");
- }
- if(obj.filteredAssets > 0) {
- colors.normal(" ");
- if(obj.assets.length > 0)
- colors.normal("+ ");
- colors.normal(obj.filteredAssets);
- if(obj.assets.length > 0)
- colors.normal(" hidden");
- colors.normal(obj.filteredAssets !== 1 ? " assets" : " asset");
- newline();
- }
- if(obj.entrypoints) {
- Object.keys(obj.entrypoints).forEach(name => {
- const ep = obj.entrypoints[name];
- colors.normal("Entrypoint ");
- colors.bold(name);
- if(ep.isOverSizeLimit) {
- colors.normal(" ");
- colors.yellow("[big]");
- }
- colors.normal(" =");
- ep.assets.forEach(asset => {
- colors.normal(" ");
- colors.green(asset);
- });
- newline();
- });
- }
- const modulesByIdentifier = {};
- if(obj.modules) {
- obj.modules.forEach(module => {
- modulesByIdentifier[`$${module.identifier}`] = module;
- });
- } else if(obj.chunks) {
- obj.chunks.forEach(chunk => {
- if(chunk.modules) {
- chunk.modules.forEach(module => {
- modulesByIdentifier[`$${module.identifier}`] = module;
- });
- }
- });
- }
-
- const processModuleAttributes = (module) => {
- colors.normal(" ");
- colors.normal(SizeFormatHelpers.formatSize(module.size));
- if(module.chunks) {
- module.chunks.forEach(chunk => {
- colors.normal(" {");
- colors.yellow(chunk);
- colors.normal("}");
- });
- }
- if(typeof module.depth === "number") {
- colors.normal(` [depth ${module.depth}]`);
- }
- if(!module.cacheable) {
- colors.red(" [not cacheable]");
- }
- if(module.optional) {
- colors.yellow(" [optional]");
- }
- if(module.built) {
- colors.green(" [built]");
- }
- if(module.prefetched) {
- colors.magenta(" [prefetched]");
- }
- if(module.failed)
- colors.red(" [failed]");
- if(module.warnings)
- colors.yellow(` [${module.warnings} warning${module.warnings === 1 ? "" : "s"}]`);
- if(module.errors)
- colors.red(` [${module.errors} error${module.errors === 1 ? "" : "s"}]`);
- };
-
- const processModuleContent = (module, prefix) => {
- if(Array.isArray(module.providedExports)) {
- colors.normal(prefix);
- if(module.providedExports.length === 0)
- colors.cyan("[no exports]");
- else
- colors.cyan(`[exports: ${module.providedExports.join(", ")}]`);
- newline();
- }
- if(module.usedExports !== undefined) {
- if(module.usedExports !== true) {
- colors.normal(prefix);
- if(module.usedExports === false || module.usedExports.length === 0)
- colors.cyan("[no exports used]");
- else
- colors.cyan(`[only some exports used: ${module.usedExports.join(", ")}]`);
- newline();
- }
- }
- if(Array.isArray(module.optimizationBailout)) {
- module.optimizationBailout.forEach(item => {
- colors.normal(prefix);
- colors.yellow(item);
- newline();
- });
- }
- if(module.reasons) {
- module.reasons.forEach(reason => {
- colors.normal(prefix);
- colors.normal(reason.type);
- colors.normal(" ");
- colors.cyan(reason.userRequest);
- colors.normal(" [");
- colors.normal(reason.moduleId);
- colors.normal("] ");
- colors.magenta(reason.module);
- if(reason.loc) {
- colors.normal(" ");
- colors.normal(reason.loc);
- }
- newline();
- });
- }
- if(module.profile) {
- colors.normal(prefix);
- let sum = 0;
- const path = [];
- let current = module;
- while(current.issuer) {
- path.push(current = current.issuer);
- }
- path.reverse().forEach(module => {
- colors.normal("[");
- colors.normal(module.id);
- colors.normal("] ");
- if(module.profile) {
- const time = (module.profile.factory || 0) + (module.profile.building || 0);
- coloredTime(time);
- sum += time;
- colors.normal(" ");
- }
- colors.normal("->");
- });
- Object.keys(module.profile).forEach(key => {
- colors.normal(` ${key}:`);
- const time = module.profile[key];
- coloredTime(time);
- sum += time;
- });
- colors.normal(" = ");
- coloredTime(sum);
- newline();
- }
- };
-
- const processModulesList = (obj, prefix) => {
- if(obj.modules) {
- obj.modules.forEach(module => {
- colors.normal(prefix);
- if(module.id < 1000) colors.normal(" ");
- if(module.id < 100) colors.normal(" ");
- if(module.id < 10) colors.normal(" ");
- colors.normal("[");
- colors.normal(module.id);
- colors.normal("] ");
- colors.bold(module.name || module.identifier);
- processModuleAttributes(module);
- newline();
- processModuleContent(module, prefix + " ");
- });
- if(obj.filteredModules > 0) {
- colors.normal(prefix);
- colors.normal(" ");
- if(obj.modules.length > 0)
- colors.normal(" + ");
- colors.normal(obj.filteredModules);
- if(obj.modules.length > 0)
- colors.normal(" hidden");
- colors.normal(obj.filteredModules !== 1 ? " modules" : " module");
- newline();
- }
- }
- };
-
- if(obj.chunks) {
- obj.chunks.forEach(chunk => {
- colors.normal("chunk ");
- if(chunk.id < 1000) colors.normal(" ");
- if(chunk.id < 100) colors.normal(" ");
- if(chunk.id < 10) colors.normal(" ");
- colors.normal("{");
- colors.yellow(chunk.id);
- colors.normal("} ");
- colors.green(chunk.files.join(", "));
- if(chunk.names && chunk.names.length > 0) {
- colors.normal(" (");
- colors.normal(chunk.names.join(", "));
- colors.normal(")");
- }
- colors.normal(" ");
- colors.normal(SizeFormatHelpers.formatSize(chunk.size));
- chunk.parents.forEach(id => {
- colors.normal(" {");
- colors.yellow(id);
- colors.normal("}");
- });
- if(chunk.entry) {
- colors.yellow(" [entry]");
- } else if(chunk.initial) {
- colors.yellow(" [initial]");
- }
- if(chunk.rendered) {
- colors.green(" [rendered]");
- }
- if(chunk.recorded) {
- colors.green(" [recorded]");
- }
- newline();
- if(chunk.origins) {
- chunk.origins.forEach(origin => {
- colors.normal(" > ");
- if(origin.reasons && origin.reasons.length) {
- colors.yellow(origin.reasons.join(" "));
- colors.normal(" ");
- }
- if(origin.name) {
- colors.normal(origin.name);
- colors.normal(" ");
- }
- if(origin.module) {
- colors.normal("[");
- colors.normal(origin.moduleId);
- colors.normal("] ");
- const module = modulesByIdentifier[`$${origin.module}`];
- if(module) {
- colors.bold(module.name);
- colors.normal(" ");
- }
- if(origin.loc) {
- colors.normal(origin.loc);
- }
- }
- newline();
- });
- }
- processModulesList(chunk, " ");
- });
- }
-
- processModulesList(obj, "");
-
- if(obj._showWarnings && obj.warnings) {
- obj.warnings.forEach(warning => {
- newline();
- colors.yellow(`WARNING in ${warning}`);
- newline();
- });
- }
- if(obj._showErrors && obj.errors) {
- obj.errors.forEach(error => {
- newline();
- colors.red(`ERROR in ${error}`);
- newline();
- });
- }
- if(obj.children) {
- obj.children.forEach(child => {
- const childString = Stats.jsonToString(child, useColors);
- if(childString) {
- if(child.name) {
- colors.normal("Child ");
- colors.bold(child.name);
- colors.normal(":");
- } else {
- colors.normal("Child");
- }
- newline();
- buf.push(" ");
- buf.push(childString.replace(/\n/g, "\n "));
- newline();
- }
- });
- }
- if(obj.needAdditionalPass) {
- colors.yellow("Compilation needs an additional pass and will compile again.");
- }
-
- while(buf[buf.length - 1] === "\n") buf.pop();
- return buf.join("");
- }
-
- static presetToOptions(name) {
- // Accepted values: none, errors-only, minimal, normal, detailed, verbose
- // Any other falsy value will behave as 'none', truthy values as 'normal'
- const pn = (typeof name === "string") && name.toLowerCase() || name || "none";
- switch(pn) {
- case "none":
- return {
- all: false
- };
- case "verbose":
- return {
- entrypoints: true,
- modules: false,
- chunks: true,
- chunkModules: true,
- chunkOrigins: true,
- depth: true,
- env: true,
- reasons: true,
- usedExports: true,
- providedExports: true,
- optimizationBailout: true,
- errorDetails: true,
- publicPath: true,
- exclude: () => false,
- maxModules: Infinity,
- };
- case "detailed":
- return {
- entrypoints: true,
- chunks: true,
- chunkModules: false,
- chunkOrigins: true,
- depth: true,
- usedExports: true,
- providedExports: true,
- optimizationBailout: true,
- errorDetails: true,
- publicPath: true,
- exclude: () => false,
- maxModules: Infinity,
- };
- case "minimal":
- return {
- all: false,
- modules: true,
- maxModules: 0,
- errors: true,
- warnings: true,
- };
- case "errors-only":
- return {
- all: false,
- errors: true,
- moduleTrace: true,
- };
- default:
- return {};
- }
- }
-
- static getChildOptions(options, idx) {
- let innerOptions;
- if(Array.isArray(options.children)) {
- if(idx < options.children.length)
- innerOptions = options.children[idx];
- } else if(typeof options.children === "object" && options.children) {
- innerOptions = options.children;
- }
- if(typeof innerOptions === "boolean" || typeof innerOptions === "string")
- innerOptions = Stats.presetToOptions(innerOptions);
- if(!innerOptions)
- return options;
- const childOptions = Object.assign({}, options);
- delete childOptions.children; // do not inherit children
- return Object.assign(childOptions, innerOptions);
- }
-}
-
-module.exports = Stats;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const RequestShortener = require("./RequestShortener"); +const SizeFormatHelpers = require("./SizeFormatHelpers"); +const formatLocation = require("./formatLocation"); +const identifierUtils = require("./util/identifier"); +const compareLocations = require("./compareLocations"); + +const optionsOrFallback = (...args) => { + let optionValues = []; + optionValues.push(...args); + return optionValues.find(optionValue => optionValue !== undefined); +}; + +const compareId = (a, b) => { + if (a < b) return -1; + if (a > b) return 1; + return 0; +}; + +class Stats { + constructor(compilation) { + this.compilation = compilation; + this.hash = compilation.hash; + this.startTime = undefined; + this.endTime = undefined; + } + + static filterWarnings(warnings, warningsFilter) { + // we dont have anything to filter so all warnings can be shown + if (!warningsFilter) { + return warnings; + } + + // create a chain of filters + // if they return "true" a warning should be suppressed + const normalizedWarningsFilters = [].concat(warningsFilter).map(filter => { + if (typeof filter === "string") { + return warning => warning.includes(filter); + } + + if (filter instanceof RegExp) { + return warning => filter.test(warning); + } + + if (typeof filter === "function") { + return filter; + } + + throw new Error( + `Can only filter warnings with Strings or RegExps. (Given: ${filter})` + ); + }); + return warnings.filter(warning => { + return !normalizedWarningsFilters.some(check => check(warning)); + }); + } + + formatFilePath(filePath) { + const OPTIONS_REGEXP = /^(\s|\S)*!/; + return filePath.includes("!") + ? `${filePath.replace(OPTIONS_REGEXP, "")} (${filePath})` + : `${filePath}`; + } + + hasWarnings() { + return ( + this.compilation.warnings.length > 0 || + this.compilation.children.some(child => child.getStats().hasWarnings()) + ); + } + + hasErrors() { + return ( + this.compilation.errors.length > 0 || + this.compilation.children.some(child => child.getStats().hasErrors()) + ); + } + + // remove a prefixed "!" that can be specified to reverse sort order + normalizeFieldKey(field) { + if (field[0] === "!") { + return field.substr(1); + } + return field; + } + + // if a field is prefixed by a "!" reverse sort order + sortOrderRegular(field) { + if (field[0] === "!") { + return false; + } + return true; + } + + toJson(options, forToString) { + if (typeof options === "boolean" || typeof options === "string") { + options = Stats.presetToOptions(options); + } else if (!options) { + options = {}; + } + + const optionOrLocalFallback = (v, def) => + v !== undefined ? v : options.all !== undefined ? options.all : def; + + const testAgainstGivenOption = item => { + if (typeof item === "string") { + const regExp = new RegExp( + `[\\\\/]${item.replace( + // eslint-disable-next-line no-useless-escape + /[-[\]{}()*+?.\\^$|]/g, + "\\$&" + )}([\\\\/]|$|!|\\?)` + ); + return ident => regExp.test(ident); + } + if (item && typeof item === "object" && typeof item.test === "function") { + return ident => item.test(ident); + } + if (typeof item === "function") { + return item; + } + if (typeof item === "boolean") { + return () => item; + } + }; + + const compilation = this.compilation; + const context = optionsOrFallback( + options.context, + compilation.compiler.context + ); + const requestShortener = + compilation.compiler.context === context + ? compilation.requestShortener + : new RequestShortener(context); + const showPerformance = optionOrLocalFallback(options.performance, true); + const showHash = optionOrLocalFallback(options.hash, true); + const showEnv = optionOrLocalFallback(options.env, false); + const showVersion = optionOrLocalFallback(options.version, true); + const showTimings = optionOrLocalFallback(options.timings, true); + const showBuiltAt = optionOrLocalFallback(options.builtAt, true); + const showAssets = optionOrLocalFallback(options.assets, true); + const showEntrypoints = optionOrLocalFallback(options.entrypoints, true); + const showChunkGroups = optionOrLocalFallback( + options.chunkGroups, + !forToString + ); + const showChunks = optionOrLocalFallback(options.chunks, !forToString); + const showChunkModules = optionOrLocalFallback(options.chunkModules, true); + const showChunkOrigins = optionOrLocalFallback( + options.chunkOrigins, + !forToString + ); + const showModules = optionOrLocalFallback(options.modules, true); + const showNestedModules = optionOrLocalFallback( + options.nestedModules, + true + ); + const showModuleAssets = optionOrLocalFallback( + options.moduleAssets, + !forToString + ); + const showDepth = optionOrLocalFallback(options.depth, !forToString); + const showCachedModules = optionOrLocalFallback(options.cached, true); + const showCachedAssets = optionOrLocalFallback(options.cachedAssets, true); + const showReasons = optionOrLocalFallback(options.reasons, !forToString); + const showUsedExports = optionOrLocalFallback( + options.usedExports, + !forToString + ); + const showProvidedExports = optionOrLocalFallback( + options.providedExports, + !forToString + ); + const showOptimizationBailout = optionOrLocalFallback( + options.optimizationBailout, + !forToString + ); + const showChildren = optionOrLocalFallback(options.children, true); + const showSource = optionOrLocalFallback(options.source, !forToString); + const showModuleTrace = optionOrLocalFallback(options.moduleTrace, true); + const showErrors = optionOrLocalFallback(options.errors, true); + const showErrorDetails = optionOrLocalFallback( + options.errorDetails, + !forToString + ); + const showWarnings = optionOrLocalFallback(options.warnings, true); + const warningsFilter = optionsOrFallback(options.warningsFilter, null); + const showPublicPath = optionOrLocalFallback( + options.publicPath, + !forToString + ); + const excludeModules = [] + .concat(optionsOrFallback(options.excludeModules, options.exclude, [])) + .map(testAgainstGivenOption); + const excludeAssets = [] + .concat(optionsOrFallback(options.excludeAssets, [])) + .map(testAgainstGivenOption); + const maxModules = optionsOrFallback( + options.maxModules, + forToString ? 15 : Infinity + ); + const sortModules = optionsOrFallback(options.modulesSort, "id"); + const sortChunks = optionsOrFallback(options.chunksSort, "id"); + const sortAssets = optionsOrFallback(options.assetsSort, ""); + const showOutputPath = optionOrLocalFallback( + options.outputPath, + !forToString + ); + + if (!showCachedModules) { + excludeModules.push((ident, module) => !module.built); + } + + const createModuleFilter = () => { + let i = 0; + return module => { + if (excludeModules.length > 0) { + const ident = requestShortener.shorten(module.resource); + const excluded = excludeModules.some(fn => fn(ident, module)); + if (excluded) return false; + } + const result = i < maxModules; + i++; + return result; + }; + }; + + const createAssetFilter = () => { + return asset => { + if (excludeAssets.length > 0) { + const ident = asset.name; + const excluded = excludeAssets.some(fn => fn(ident, asset)); + if (excluded) return false; + } + return showCachedAssets || asset.emitted; + }; + }; + + const sortByFieldAndOrder = (fieldKey, a, b) => { + if (a[fieldKey] === null && b[fieldKey] === null) return 0; + if (a[fieldKey] === null) return 1; + if (b[fieldKey] === null) return -1; + if (a[fieldKey] === b[fieldKey]) return 0; + return a[fieldKey] < b[fieldKey] ? -1 : 1; + }; + + const sortByField = field => (a, b) => { + if (!field) { + return 0; + } + + const fieldKey = this.normalizeFieldKey(field); + + // if a field is prefixed with a "!" the sort is reversed! + const sortIsRegular = this.sortOrderRegular(field); + + return sortByFieldAndOrder( + fieldKey, + sortIsRegular ? a : b, + sortIsRegular ? b : a + ); + }; + + const formatError = e => { + let text = ""; + if (typeof e === "string") { + e = { message: e }; + } + if (e.chunk) { + text += `chunk ${e.chunk.name || e.chunk.id}${ + e.chunk.hasRuntime() + ? " [entry]" + : e.chunk.canBeInitial() + ? " [initial]" + : "" + }\n`; + } + if (e.file) { + text += `${e.file}\n`; + } + if ( + e.module && + e.module.readableIdentifier && + typeof e.module.readableIdentifier === "function" + ) { + text += this.formatFilePath( + e.module.readableIdentifier(requestShortener) + ); + if (typeof e.loc === "object") { + const locInfo = formatLocation(e.loc); + if (locInfo) text += ` ${locInfo}`; + } + text += "\n"; + } + text += e.message; + if (showErrorDetails && e.details) { + text += `\n${e.details}`; + } + if (showErrorDetails && e.missing) { + text += e.missing.map(item => `\n[${item}]`).join(""); + } + if (showModuleTrace && e.origin) { + text += `\n @ ${this.formatFilePath( + e.origin.readableIdentifier(requestShortener) + )}`; + if (typeof e.originLoc === "object") { + const locInfo = formatLocation(e.originLoc); + if (locInfo) text += ` ${locInfo}`; + } + if (e.dependencies) { + for (const dep of e.dependencies) { + if (!dep.loc) continue; + if (typeof dep.loc === "string") continue; + const locInfo = formatLocation(dep.loc); + if (!locInfo) continue; + text += ` ${locInfo}`; + } + } + let current = e.origin; + while (current.issuer) { + current = current.issuer; + text += `\n @ ${current.readableIdentifier(requestShortener)}`; + } + } + return text; + }; + + const obj = { + errors: compilation.errors.map(formatError), + warnings: Stats.filterWarnings( + compilation.warnings.map(formatError), + warningsFilter + ) + }; + + //We just hint other renderers since actually omitting + //errors/warnings from the JSON would be kind of weird. + Object.defineProperty(obj, "_showWarnings", { + value: showWarnings, + enumerable: false + }); + Object.defineProperty(obj, "_showErrors", { + value: showErrors, + enumerable: false + }); + + if (showVersion) { + obj.version = require("../package.json").version; + } + + if (showHash) obj.hash = this.hash; + if (showTimings && this.startTime && this.endTime) { + obj.time = this.endTime - this.startTime; + } + + if (showBuiltAt && this.endTime) { + obj.builtAt = this.endTime; + } + + if (showEnv && options._env) { + obj.env = options._env; + } + + if (compilation.needAdditionalPass) { + obj.needAdditionalPass = true; + } + if (showPublicPath) { + obj.publicPath = this.compilation.mainTemplate.getPublicPath({ + hash: this.compilation.hash + }); + } + if (showOutputPath) { + obj.outputPath = this.compilation.mainTemplate.outputOptions.path; + } + if (showAssets) { + const assetsByFile = {}; + const compilationAssets = Object.keys(compilation.assets); + obj.assetsByChunkName = {}; + obj.assets = compilationAssets + .map(asset => { + const obj = { + name: asset, + size: compilation.assets[asset].size(), + chunks: [], + chunkNames: [], + emitted: compilation.assets[asset].emitted + }; + + if (showPerformance) { + obj.isOverSizeLimit = compilation.assets[asset].isOverSizeLimit; + } + + assetsByFile[asset] = obj; + return obj; + }) + .filter(createAssetFilter()); + obj.filteredAssets = compilationAssets.length - obj.assets.length; + + for (const chunk of compilation.chunks) { + for (const asset of chunk.files) { + if (assetsByFile[asset]) { + for (const id of chunk.ids) { + assetsByFile[asset].chunks.push(id); + } + if (chunk.name) { + assetsByFile[asset].chunkNames.push(chunk.name); + if (obj.assetsByChunkName[chunk.name]) { + obj.assetsByChunkName[chunk.name] = [] + .concat(obj.assetsByChunkName[chunk.name]) + .concat([asset]); + } else { + obj.assetsByChunkName[chunk.name] = asset; + } + } + } + } + } + obj.assets.sort(sortByField(sortAssets)); + } + + const fnChunkGroup = groupMap => { + const obj = {}; + for (const keyValuePair of groupMap) { + const name = keyValuePair[0]; + const cg = keyValuePair[1]; + const children = cg.getChildrenByOrders(); + obj[name] = { + chunks: cg.chunks.map(c => c.id), + assets: cg.chunks.reduce( + (array, c) => array.concat(c.files || []), + [] + ), + children: Object.keys(children).reduce((obj, key) => { + const groups = children[key]; + obj[key] = groups.map(group => ({ + name: group.name, + chunks: group.chunks.map(c => c.id), + assets: group.chunks.reduce( + (array, c) => array.concat(c.files || []), + [] + ) + })); + return obj; + }, Object.create(null)), + childAssets: Object.keys(children).reduce((obj, key) => { + const groups = children[key]; + obj[key] = Array.from( + groups.reduce((set, group) => { + for (const chunk of group.chunks) { + for (const asset of chunk.files) { + set.add(asset); + } + } + return set; + }, new Set()) + ); + return obj; + }, Object.create(null)) + }; + if (showPerformance) { + obj[name].isOverSizeLimit = cg.isOverSizeLimit; + } + } + + return obj; + }; + + if (showEntrypoints) { + obj.entrypoints = fnChunkGroup(compilation.entrypoints); + } + + if (showChunkGroups) { + obj.namedChunkGroups = fnChunkGroup(compilation.namedChunkGroups); + } + + const fnModule = module => { + const path = []; + let current = module; + while (current.issuer) { + path.push((current = current.issuer)); + } + path.reverse(); + const obj = { + id: module.id, + identifier: module.identifier(), + name: module.readableIdentifier(requestShortener), + index: module.index, + index2: module.index2, + size: module.size(), + cacheable: module.buildInfo.cacheable, + built: !!module.built, + optional: module.optional, + prefetched: module.prefetched, + chunks: Array.from(module.chunksIterable, chunk => chunk.id), + issuer: module.issuer && module.issuer.identifier(), + issuerId: module.issuer && module.issuer.id, + issuerName: + module.issuer && module.issuer.readableIdentifier(requestShortener), + issuerPath: + module.issuer && + path.map(module => ({ + id: module.id, + identifier: module.identifier(), + name: module.readableIdentifier(requestShortener), + profile: module.profile + })), + profile: module.profile, + failed: !!module.error, + errors: module.errors ? module.errors.length : 0, + warnings: module.warnings ? module.warnings.length : 0 + }; + if (showModuleAssets) { + obj.assets = Object.keys(module.buildInfo.assets || {}); + } + if (showReasons) { + obj.reasons = module.reasons + .sort((a, b) => { + if (a.module && !b.module) return -1; + if (!a.module && b.module) return 1; + if (a.module && b.module) { + const cmp = compareId(a.module.id, b.module.id); + if (cmp) return cmp; + } + if (a.dependency && !b.dependency) return -1; + if (!a.dependency && b.dependency) return 1; + if (a.dependency && b.dependency) { + const cmp = compareLocations(a.dependency.loc, b.dependency.loc); + if (cmp) return cmp; + if (a.dependency.type < b.dependency.type) return -1; + if (a.dependency.type > b.dependency.type) return 1; + } + return 0; + }) + .map(reason => { + const obj = { + moduleId: reason.module ? reason.module.id : null, + moduleIdentifier: reason.module + ? reason.module.identifier() + : null, + module: reason.module + ? reason.module.readableIdentifier(requestShortener) + : null, + moduleName: reason.module + ? reason.module.readableIdentifier(requestShortener) + : null, + type: reason.dependency ? reason.dependency.type : null, + explanation: reason.explanation, + userRequest: reason.dependency + ? reason.dependency.userRequest + : null + }; + if (reason.dependency) { + const locInfo = formatLocation(reason.dependency.loc); + if (locInfo) { + obj.loc = locInfo; + } + } + return obj; + }); + } + if (showUsedExports) { + if (module.used === true) { + obj.usedExports = module.usedExports; + } else if (module.used === false) { + obj.usedExports = false; + } + } + if (showProvidedExports) { + obj.providedExports = Array.isArray(module.buildMeta.providedExports) + ? module.buildMeta.providedExports + : null; + } + if (showOptimizationBailout) { + obj.optimizationBailout = module.optimizationBailout.map(item => { + if (typeof item === "function") return item(requestShortener); + return item; + }); + } + if (showDepth) { + obj.depth = module.depth; + } + if (showNestedModules) { + if (module.modules) { + const modules = module.modules; + obj.modules = modules + .sort(sortByField("depth")) + .filter(createModuleFilter()) + .map(fnModule); + obj.filteredModules = modules.length - obj.modules.length; + obj.modules.sort(sortByField(sortModules)); + } + } + if (showSource && module._source) { + obj.source = module._source.source(); + } + return obj; + }; + if (showChunks) { + obj.chunks = compilation.chunks.map(chunk => { + const parents = new Set(); + const children = new Set(); + const siblings = new Set(); + const childIdByOrder = chunk.getChildIdsByOrders(); + for (const chunkGroup of chunk.groupsIterable) { + for (const parentGroup of chunkGroup.parentsIterable) { + for (const chunk of parentGroup.chunks) { + parents.add(chunk.id); + } + } + for (const childGroup of chunkGroup.childrenIterable) { + for (const chunk of childGroup.chunks) { + children.add(chunk.id); + } + } + for (const sibling of chunkGroup.chunks) { + if (sibling !== chunk) siblings.add(sibling.id); + } + } + const obj = { + id: chunk.id, + rendered: chunk.rendered, + initial: chunk.canBeInitial(), + entry: chunk.hasRuntime(), + recorded: chunk.recorded, + reason: chunk.chunkReason, + size: chunk.modulesSize(), + names: chunk.name ? [chunk.name] : [], + files: chunk.files.slice(), + hash: chunk.renderedHash, + siblings: Array.from(siblings).sort(compareId), + parents: Array.from(parents).sort(compareId), + children: Array.from(children).sort(compareId), + childrenByOrder: childIdByOrder + }; + if (showChunkModules) { + obj.modules = chunk + .getModules() + .sort(sortByField("depth")) + .filter(createModuleFilter()) + .map(fnModule); + obj.filteredModules = chunk.getNumberOfModules() - obj.modules.length; + obj.modules.sort(sortByField(sortModules)); + } + if (showChunkOrigins) { + obj.origins = Array.from(chunk.groupsIterable, g => g.origins) + .reduce((a, b) => a.concat(b), []) + .map(origin => ({ + moduleId: origin.module ? origin.module.id : undefined, + module: origin.module ? origin.module.identifier() : "", + moduleIdentifier: origin.module ? origin.module.identifier() : "", + moduleName: origin.module + ? origin.module.readableIdentifier(requestShortener) + : "", + loc: formatLocation(origin.loc), + request: origin.request, + reasons: origin.reasons || [] + })) + .sort((a, b) => { + if ( + typeof a.moduleId === "number" && + typeof b.moduleId !== "number" + ) + return 1; + if ( + typeof a.moduleId !== "number" && + typeof b.moduleId === "number" + ) + return -1; + if ( + typeof a.moduleId === "number" && + typeof b.moduleId === "number" + ) { + const diffId = a.moduleId - b.moduleId; + if (diffId !== 0) return diffId; + } + if (a.loc < b.loc) return -1; + if (a.loc > b.loc) return 1; + return 0; + }); + } + return obj; + }); + obj.chunks.sort(sortByField(sortChunks)); + } + if (showModules) { + obj.modules = compilation.modules + .slice() + .sort(sortByField("depth")) + .filter(createModuleFilter()) + .map(fnModule); + obj.filteredModules = compilation.modules.length - obj.modules.length; + obj.modules.sort(sortByField(sortModules)); + } + if (showChildren) { + obj.children = compilation.children.map((child, idx) => { + const childOptions = Stats.getChildOptions(options, idx); + const obj = new Stats(child).toJson(childOptions, forToString); + delete obj.hash; + delete obj.version; + if (child.name) { + obj.name = identifierUtils.makePathsRelative( + context, + child.name, + compilation.cache + ); + } + return obj; + }); + } + + return obj; + } + + toString(options) { + if (typeof options === "boolean" || typeof options === "string") { + options = Stats.presetToOptions(options); + } else if (!options) { + options = {}; + } + + const useColors = optionsOrFallback(options.colors, false); + + const obj = this.toJson(options, true); + + return Stats.jsonToString(obj, useColors); + } + + static jsonToString(obj, useColors) { + const buf = []; + + const defaultColors = { + bold: "\u001b[1m", + yellow: "\u001b[1m\u001b[33m", + red: "\u001b[1m\u001b[31m", + green: "\u001b[1m\u001b[32m", + cyan: "\u001b[1m\u001b[36m", + magenta: "\u001b[1m\u001b[35m" + }; + + const colors = Object.keys(defaultColors).reduce( + (obj, color) => { + obj[color] = str => { + if (useColors) { + buf.push( + useColors === true || useColors[color] === undefined + ? defaultColors[color] + : useColors[color] + ); + } + buf.push(str); + if (useColors) { + buf.push("\u001b[39m\u001b[22m"); + } + }; + return obj; + }, + { + normal: str => buf.push(str) + } + ); + + const coloredTime = time => { + let times = [800, 400, 200, 100]; + if (obj.time) { + times = [obj.time / 2, obj.time / 4, obj.time / 8, obj.time / 16]; + } + if (time < times[3]) colors.normal(`${time}ms`); + else if (time < times[2]) colors.bold(`${time}ms`); + else if (time < times[1]) colors.green(`${time}ms`); + else if (time < times[0]) colors.yellow(`${time}ms`); + else colors.red(`${time}ms`); + }; + + const newline = () => buf.push("\n"); + + const getText = (arr, row, col) => { + return arr[row][col].value; + }; + + const table = (array, align, splitter) => { + const rows = array.length; + const cols = array[0].length; + const colSizes = new Array(cols); + for (let col = 0; col < cols; col++) { + colSizes[col] = 0; + } + for (let row = 0; row < rows; row++) { + for (let col = 0; col < cols; col++) { + const value = `${getText(array, row, col)}`; + if (value.length > colSizes[col]) { + colSizes[col] = value.length; + } + } + } + for (let row = 0; row < rows; row++) { + for (let col = 0; col < cols; col++) { + const format = array[row][col].color; + const value = `${getText(array, row, col)}`; + let l = value.length; + if (align[col] === "l") { + format(value); + } + for (; l < colSizes[col] && col !== cols - 1; l++) { + colors.normal(" "); + } + if (align[col] === "r") { + format(value); + } + if (col + 1 < cols && colSizes[col] !== 0) { + colors.normal(splitter || " "); + } + } + newline(); + } + }; + + const getAssetColor = (asset, defaultColor) => { + if (asset.isOverSizeLimit) { + return colors.yellow; + } + + return defaultColor; + }; + + if (obj.hash) { + colors.normal("Hash: "); + colors.bold(obj.hash); + newline(); + } + if (obj.version) { + colors.normal("Version: webpack "); + colors.bold(obj.version); + newline(); + } + if (typeof obj.time === "number") { + colors.normal("Time: "); + colors.bold(obj.time); + colors.normal("ms"); + newline(); + } + if (typeof obj.builtAt === "number") { + const builtAtDate = new Date(obj.builtAt); + colors.normal("Built at: "); + colors.normal( + builtAtDate.toLocaleDateString(undefined, { + day: "2-digit", + month: "2-digit", + year: "numeric" + }) + ); + colors.normal(" "); + colors.bold(builtAtDate.toLocaleTimeString()); + newline(); + } + if (obj.env) { + colors.normal("Environment (--env): "); + colors.bold(JSON.stringify(obj.env, null, 2)); + newline(); + } + if (obj.publicPath) { + colors.normal("PublicPath: "); + colors.bold(obj.publicPath); + newline(); + } + + if (obj.assets && obj.assets.length > 0) { + const t = [ + [ + { + value: "Asset", + color: colors.bold + }, + { + value: "Size", + color: colors.bold + }, + { + value: "Chunks", + color: colors.bold + }, + { + value: "", + color: colors.bold + }, + { + value: "", + color: colors.bold + }, + { + value: "Chunk Names", + color: colors.bold + } + ] + ]; + for (const asset of obj.assets) { + t.push([ + { + value: asset.name, + color: getAssetColor(asset, colors.green) + }, + { + value: SizeFormatHelpers.formatSize(asset.size), + color: getAssetColor(asset, colors.normal) + }, + { + value: asset.chunks.join(", "), + color: colors.bold + }, + { + value: asset.emitted ? "[emitted]" : "", + color: colors.green + }, + { + value: asset.isOverSizeLimit ? "[big]" : "", + color: getAssetColor(asset, colors.normal) + }, + { + value: asset.chunkNames.join(", "), + color: colors.normal + } + ]); + } + table(t, "rrrlll"); + } + if (obj.filteredAssets > 0) { + colors.normal(" "); + if (obj.assets.length > 0) colors.normal("+ "); + colors.normal(obj.filteredAssets); + if (obj.assets.length > 0) colors.normal(" hidden"); + colors.normal(obj.filteredAssets !== 1 ? " assets" : " asset"); + newline(); + } + + const processChunkGroups = (namedGroups, prefix) => { + for (const name of Object.keys(namedGroups)) { + const cg = namedGroups[name]; + colors.normal(`${prefix} `); + colors.bold(name); + if (cg.isOverSizeLimit) { + colors.normal(" "); + colors.yellow("[big]"); + } + colors.normal(" ="); + for (const asset of cg.assets) { + colors.normal(" "); + colors.green(asset); + } + for (const name of Object.keys(cg.childAssets)) { + const assets = cg.childAssets[name]; + if (assets && assets.length > 0) { + colors.normal(" "); + colors.magenta(`(${name}:`); + for (const asset of assets) { + colors.normal(" "); + colors.green(asset); + } + colors.magenta(")"); + } + } + newline(); + } + }; + + if (obj.entrypoints) { + processChunkGroups(obj.entrypoints, "Entrypoint"); + } + + if (obj.namedChunkGroups) { + let outputChunkGroups = obj.namedChunkGroups; + if (obj.entrypoints) { + outputChunkGroups = Object.keys(outputChunkGroups) + .filter(name => !obj.entrypoints[name]) + .reduce((result, name) => { + result[name] = obj.namedChunkGroups[name]; + return result; + }, {}); + } + processChunkGroups(outputChunkGroups, "Chunk Group"); + } + + const modulesByIdentifier = {}; + if (obj.modules) { + for (const module of obj.modules) { + modulesByIdentifier[`$${module.identifier}`] = module; + } + } else if (obj.chunks) { + for (const chunk of obj.chunks) { + if (chunk.modules) { + for (const module of chunk.modules) { + modulesByIdentifier[`$${module.identifier}`] = module; + } + } + } + } + + const processModuleAttributes = module => { + colors.normal(" "); + colors.normal(SizeFormatHelpers.formatSize(module.size)); + if (module.chunks) { + for (const chunk of module.chunks) { + colors.normal(" {"); + colors.yellow(chunk); + colors.normal("}"); + } + } + if (typeof module.depth === "number") { + colors.normal(` [depth ${module.depth}]`); + } + if (module.cacheable === false) { + colors.red(" [not cacheable]"); + } + if (module.optional) { + colors.yellow(" [optional]"); + } + if (module.built) { + colors.green(" [built]"); + } + if (module.assets && module.assets.length) { + colors.magenta( + ` [${module.assets.length} asset${ + module.assets.length === 1 ? "" : "s" + }]` + ); + } + if (module.prefetched) { + colors.magenta(" [prefetched]"); + } + if (module.failed) colors.red(" [failed]"); + if (module.warnings) { + colors.yellow( + ` [${module.warnings} warning${module.warnings === 1 ? "" : "s"}]` + ); + } + if (module.errors) { + colors.red( + ` [${module.errors} error${module.errors === 1 ? "" : "s"}]` + ); + } + }; + + const processModuleContent = (module, prefix) => { + if (Array.isArray(module.providedExports)) { + colors.normal(prefix); + if (module.providedExports.length === 0) { + colors.cyan("[no exports]"); + } else { + colors.cyan(`[exports: ${module.providedExports.join(", ")}]`); + } + newline(); + } + if (module.usedExports !== undefined) { + if (module.usedExports !== true) { + colors.normal(prefix); + if (module.usedExports === null) { + colors.cyan("[used exports unknown]"); + } else if (module.usedExports === false) { + colors.cyan("[no exports used]"); + } else if ( + Array.isArray(module.usedExports) && + module.usedExports.length === 0 + ) { + colors.cyan("[no exports used]"); + } else if (Array.isArray(module.usedExports)) { + const providedExportsCount = Array.isArray(module.providedExports) + ? module.providedExports.length + : null; + if ( + providedExportsCount !== null && + providedExportsCount === module.usedExports.length + ) { + colors.cyan("[all exports used]"); + } else { + colors.cyan( + `[only some exports used: ${module.usedExports.join(", ")}]` + ); + } + } + newline(); + } + } + if (Array.isArray(module.optimizationBailout)) { + for (const item of module.optimizationBailout) { + colors.normal(prefix); + colors.yellow(item); + newline(); + } + } + if (module.reasons) { + for (const reason of module.reasons) { + colors.normal(prefix); + if (reason.type) { + colors.normal(reason.type); + colors.normal(" "); + } + if (reason.userRequest) { + colors.cyan(reason.userRequest); + colors.normal(" "); + } + if (reason.moduleId !== null) { + colors.normal("["); + colors.normal(reason.moduleId); + colors.normal("]"); + } + if (reason.module && reason.module !== reason.moduleId) { + colors.normal(" "); + colors.magenta(reason.module); + } + if (reason.loc) { + colors.normal(" "); + colors.normal(reason.loc); + } + if (reason.explanation) { + colors.normal(" "); + colors.cyan(reason.explanation); + } + newline(); + } + } + if (module.profile) { + colors.normal(prefix); + let sum = 0; + if (module.issuerPath) { + for (const m of module.issuerPath) { + colors.normal("["); + colors.normal(m.id); + colors.normal("] "); + if (m.profile) { + const time = (m.profile.factory || 0) + (m.profile.building || 0); + coloredTime(time); + sum += time; + colors.normal(" "); + } + colors.normal("-> "); + } + } + for (const key of Object.keys(module.profile)) { + colors.normal(`${key}:`); + const time = module.profile[key]; + coloredTime(time); + colors.normal(" "); + sum += time; + } + colors.normal("= "); + coloredTime(sum); + newline(); + } + if (module.modules) { + processModulesList(module, prefix + "| "); + } + }; + + const processModulesList = (obj, prefix) => { + if (obj.modules) { + let maxModuleId = 0; + for (const module of obj.modules) { + if (typeof module.id === "number") { + if (maxModuleId < module.id) maxModuleId = module.id; + } + } + let contentPrefix = prefix + " "; + if (maxModuleId >= 10) contentPrefix += " "; + if (maxModuleId >= 100) contentPrefix += " "; + if (maxModuleId >= 1000) contentPrefix += " "; + for (const module of obj.modules) { + colors.normal(prefix); + const name = module.name || module.identifier; + if (typeof module.id === "string" || typeof module.id === "number") { + if (typeof module.id === "number") { + if (module.id < 1000 && maxModuleId >= 1000) colors.normal(" "); + if (module.id < 100 && maxModuleId >= 100) colors.normal(" "); + if (module.id < 10 && maxModuleId >= 10) colors.normal(" "); + } else { + if (maxModuleId >= 1000) colors.normal(" "); + if (maxModuleId >= 100) colors.normal(" "); + if (maxModuleId >= 10) colors.normal(" "); + } + if (name !== module.id) { + colors.normal("["); + colors.normal(module.id); + colors.normal("]"); + colors.normal(" "); + } else { + colors.normal("["); + colors.bold(module.id); + colors.normal("]"); + } + } + if (name !== module.id) { + colors.bold(name); + } + processModuleAttributes(module); + newline(); + processModuleContent(module, contentPrefix); + } + if (obj.filteredModules > 0) { + colors.normal(prefix); + colors.normal(" "); + if (obj.modules.length > 0) colors.normal(" + "); + colors.normal(obj.filteredModules); + if (obj.modules.length > 0) colors.normal(" hidden"); + colors.normal(obj.filteredModules !== 1 ? " modules" : " module"); + newline(); + } + } + }; + + if (obj.chunks) { + for (const chunk of obj.chunks) { + colors.normal("chunk "); + if (chunk.id < 1000) colors.normal(" "); + if (chunk.id < 100) colors.normal(" "); + if (chunk.id < 10) colors.normal(" "); + colors.normal("{"); + colors.yellow(chunk.id); + colors.normal("} "); + colors.green(chunk.files.join(", ")); + if (chunk.names && chunk.names.length > 0) { + colors.normal(" ("); + colors.normal(chunk.names.join(", ")); + colors.normal(")"); + } + colors.normal(" "); + colors.normal(SizeFormatHelpers.formatSize(chunk.size)); + for (const id of chunk.parents) { + colors.normal(" <{"); + colors.yellow(id); + colors.normal("}>"); + } + for (const id of chunk.siblings) { + colors.normal(" ={"); + colors.yellow(id); + colors.normal("}="); + } + for (const id of chunk.children) { + colors.normal(" >{"); + colors.yellow(id); + colors.normal("}<"); + } + if (chunk.childrenByOrder) { + for (const name of Object.keys(chunk.childrenByOrder)) { + const children = chunk.childrenByOrder[name]; + colors.normal(" "); + colors.magenta(`(${name}:`); + for (const id of children) { + colors.normal(" {"); + colors.yellow(id); + colors.normal("}"); + } + colors.magenta(")"); + } + } + if (chunk.entry) { + colors.yellow(" [entry]"); + } else if (chunk.initial) { + colors.yellow(" [initial]"); + } + if (chunk.rendered) { + colors.green(" [rendered]"); + } + if (chunk.recorded) { + colors.green(" [recorded]"); + } + if (chunk.reason) { + colors.yellow(` ${chunk.reason}`); + } + newline(); + if (chunk.origins) { + for (const origin of chunk.origins) { + colors.normal(" > "); + if (origin.reasons && origin.reasons.length) { + colors.yellow(origin.reasons.join(" ")); + colors.normal(" "); + } + if (origin.request) { + colors.normal(origin.request); + colors.normal(" "); + } + if (origin.module) { + colors.normal("["); + colors.normal(origin.moduleId); + colors.normal("] "); + const module = modulesByIdentifier[`$${origin.module}`]; + if (module) { + colors.bold(module.name); + colors.normal(" "); + } + } + if (origin.loc) { + colors.normal(origin.loc); + } + newline(); + } + } + processModulesList(chunk, " "); + } + } + + processModulesList(obj, ""); + + if (obj._showWarnings && obj.warnings) { + for (const warning of obj.warnings) { + newline(); + colors.yellow(`WARNING in ${warning}`); + newline(); + } + } + if (obj._showErrors && obj.errors) { + for (const error of obj.errors) { + newline(); + colors.red(`ERROR in ${error}`); + newline(); + } + } + if (obj.children) { + for (const child of obj.children) { + const childString = Stats.jsonToString(child, useColors); + if (childString) { + if (child.name) { + colors.normal("Child "); + colors.bold(child.name); + colors.normal(":"); + } else { + colors.normal("Child"); + } + newline(); + buf.push(" "); + buf.push(childString.replace(/\n/g, "\n ")); + newline(); + } + } + } + if (obj.needAdditionalPass) { + colors.yellow( + "Compilation needs an additional pass and will compile again." + ); + } + + while (buf[buf.length - 1] === "\n") { + buf.pop(); + } + return buf.join(""); + } + + static presetToOptions(name) { + // Accepted values: none, errors-only, minimal, normal, detailed, verbose + // Any other falsy value will behave as 'none', truthy values as 'normal' + const pn = + (typeof name === "string" && name.toLowerCase()) || name || "none"; + switch (pn) { + case "none": + return { + all: false + }; + case "verbose": + return { + entrypoints: true, + chunkGroups: true, + modules: false, + chunks: true, + chunkModules: true, + chunkOrigins: true, + depth: true, + env: true, + reasons: true, + usedExports: true, + providedExports: true, + optimizationBailout: true, + errorDetails: true, + publicPath: true, + exclude: false, + maxModules: Infinity + }; + case "detailed": + return { + entrypoints: true, + chunkGroups: true, + chunks: true, + chunkModules: false, + chunkOrigins: true, + depth: true, + usedExports: true, + providedExports: true, + optimizationBailout: true, + errorDetails: true, + publicPath: true, + exclude: false, + maxModules: Infinity + }; + case "minimal": + return { + all: false, + modules: true, + maxModules: 0, + errors: true, + warnings: true + }; + case "errors-only": + return { + all: false, + errors: true, + moduleTrace: true + }; + default: + return {}; + } + } + + static getChildOptions(options, idx) { + let innerOptions; + if (Array.isArray(options.children)) { + if (idx < options.children.length) { + innerOptions = options.children[idx]; + } + } else if (typeof options.children === "object" && options.children) { + innerOptions = options.children; + } + if (typeof innerOptions === "boolean" || typeof innerOptions === "string") { + innerOptions = Stats.presetToOptions(innerOptions); + } + if (!innerOptions) { + return options; + } + const childOptions = Object.assign({}, options); + delete childOptions.children; // do not inherit children + return Object.assign(childOptions, innerOptions); + } +} + +module.exports = Stats; diff --git a/node_modules/webpack/lib/Template.js b/node_modules/webpack/lib/Template.js index 57a8b9730..572d4b5ed 100644 --- a/node_modules/webpack/lib/Template.js +++ b/node_modules/webpack/lib/Template.js @@ -1,176 +1,290 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const Tapable = require("tapable");
-const ConcatSource = require("webpack-sources").ConcatSource;
-
-const START_LOWERCASE_ALPHABET_CODE = "a".charCodeAt(0);
-const START_UPPERCASE_ALPHABET_CODE = "A".charCodeAt(0);
-const DELTA_A_TO_Z = "z".charCodeAt(0) - START_LOWERCASE_ALPHABET_CODE + 1;
-const FUNCTION_CONTENT_REGEX = /^function\s?\(\)\s?\{\n?|\n?\}$/g;
-const INDENT_MULTILINE_REGEX = /^\t/mg;
-const IDENTIFIER_NAME_REPLACE_REGEX = /^[^a-zA-Z$_]/;
-const IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX = /[^a-zA-Z0-9$_]/g;
-const PATH_NAME_NORMALIZE_REPLACE_REGEX = /[^a-zA-Z0-9_!§$()=\-^°]+/g;
-const MATCH_PADDED_HYPHENS_REPLACE_REGEX = /^-|-$/g;
-
-module.exports = class Template extends Tapable {
- constructor(outputOptions) {
- super();
- this.outputOptions = outputOptions || {};
- }
-
- static getFunctionContent(fn) {
- return fn.toString().replace(FUNCTION_CONTENT_REGEX, "").replace(INDENT_MULTILINE_REGEX, "");
- }
-
- static toIdentifier(str) {
- if(typeof str !== "string") return "";
- return str.replace(IDENTIFIER_NAME_REPLACE_REGEX, "_").replace(IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX, "_");
- }
-
- static toPath(str) {
- if(typeof str !== "string") return "";
- return str.replace(PATH_NAME_NORMALIZE_REPLACE_REGEX, "-").replace(MATCH_PADDED_HYPHENS_REPLACE_REGEX, "");
- }
-
- // map number to a single character a-z, A-Z or <_ + number> if number is too big
- static numberToIdentifer(n) {
- // lower case
- if(n < DELTA_A_TO_Z) return String.fromCharCode(START_LOWERCASE_ALPHABET_CODE + n);
-
- // upper case
- n -= DELTA_A_TO_Z;
- if(n < DELTA_A_TO_Z) return String.fromCharCode(START_UPPERCASE_ALPHABET_CODE + n);
-
- // fall back to _ + number
- n -= DELTA_A_TO_Z;
- return "_" + n;
- }
-
- indent(str) {
- if(Array.isArray(str)) {
- return str.map(this.indent.bind(this)).join("\n");
- } else {
- str = str.trimRight();
- if(!str) return "";
- var ind = (str[0] === "\n" ? "" : "\t");
- return ind + str.replace(/\n([^\n])/g, "\n\t$1");
- }
- }
-
- prefix(str, prefix) {
- if(Array.isArray(str)) {
- str = str.join("\n");
- }
- str = str.trim();
- if(!str) return "";
- const ind = (str[0] === "\n" ? "" : prefix);
- return ind + str.replace(/\n([^\n])/g, "\n" + prefix + "$1");
- }
-
- asString(str) {
- if(Array.isArray(str)) {
- return str.join("\n");
- }
- return str;
- }
-
- getModulesArrayBounds(modules) {
- if(!modules.every(moduleIdIsNumber))
- return false;
- var maxId = -Infinity;
- var minId = Infinity;
- modules.forEach(function(module) {
- if(maxId < module.id) maxId = module.id;
- if(minId > module.id) minId = module.id;
- });
- if(minId < 16 + ("" + minId).length) {
- // add minId x ',' instead of 'Array(minId).concat(...)'
- minId = 0;
- }
- var objectOverhead = modules.map(function(module) {
- var idLength = (module.id + "").length;
- return idLength + 2;
- }).reduce(function(a, b) {
- return a + b;
- }, -1);
- var arrayOverhead = minId === 0 ? maxId : 16 + ("" + minId).length + maxId;
- return arrayOverhead < objectOverhead ? [minId, maxId] : false;
- }
-
- renderChunkModules(chunk, moduleTemplate, dependencyTemplates, prefix) {
- if(!prefix) prefix = "";
- var source = new ConcatSource();
- if(chunk.getNumberOfModules() === 0) {
- source.add("[]");
- return source;
- }
- var removedModules = chunk.removedModules;
- var allModules = chunk.mapModules(function(module) {
- return {
- id: module.id,
- source: moduleTemplate.render(module, dependencyTemplates, chunk)
- };
- });
- if(removedModules && removedModules.length > 0) {
- removedModules.forEach(function(id) {
- allModules.push({
- id: id,
- source: "false"
- });
- });
- }
- var bounds = this.getModulesArrayBounds(allModules);
-
- if(bounds) {
- // Render a spare array
- var minId = bounds[0];
- var maxId = bounds[1];
- if(minId !== 0) source.add("Array(" + minId + ").concat(");
- source.add("[\n");
- var modules = {};
- allModules.forEach(function(module) {
- modules[module.id] = module;
- });
- for(var idx = minId; idx <= maxId; idx++) {
- var module = modules[idx];
- if(idx !== minId) source.add(",\n");
- source.add("/* " + idx + " */");
- if(module) {
- source.add("\n");
- source.add(module.source);
- }
- }
- source.add("\n" + prefix + "]");
- if(minId !== 0) source.add(")");
- } else {
- // Render an object
- source.add("{\n");
- allModules
- .sort(stringifyIdSortPredicate)
- .forEach(function(module, idx) {
- if(idx !== 0) source.add(",\n");
- source.add(`\n/***/ ${JSON.stringify(module.id)}:\n`);
- source.add(module.source);
- });
- source.add("\n\n" + prefix + "}");
- }
- return source;
- }
-};
-
-function stringifyIdSortPredicate(a, b) {
- var aId = a.id + "";
- var bId = b.id + "";
- if(aId < bId) return -1;
- if(aId > bId) return 1;
- return 0;
-}
-
-function moduleIdIsNumber(module) {
- return typeof module.id === "number";
-}
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./ModuleTemplate")} ModuleTemplate */ +/** @typedef {import("webpack-sources").ConcatSource} ConcatSource */ + +const { ConcatSource } = require("webpack-sources"); +const HotUpdateChunk = require("./HotUpdateChunk"); + +const START_LOWERCASE_ALPHABET_CODE = "a".charCodeAt(0); +const START_UPPERCASE_ALPHABET_CODE = "A".charCodeAt(0); +const DELTA_A_TO_Z = "z".charCodeAt(0) - START_LOWERCASE_ALPHABET_CODE + 1; +const FUNCTION_CONTENT_REGEX = /^function\s?\(\)\s?\{\r?\n?|\r?\n?\}$/g; +const INDENT_MULTILINE_REGEX = /^\t/gm; +const LINE_SEPARATOR_REGEX = /\r?\n/g; +const IDENTIFIER_NAME_REPLACE_REGEX = /^([^a-zA-Z$_])/; +const IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX = /[^a-zA-Z0-9$]+/g; +const COMMENT_END_REGEX = /\*\//g; +const PATH_NAME_NORMALIZE_REPLACE_REGEX = /[^a-zA-Z0-9_!§$()=\-^°]+/g; +const MATCH_PADDED_HYPHENS_REPLACE_REGEX = /^-|-$/g; + +/** @typedef {import("webpack-sources").Source} Source */ + +/** + * @typedef {Object} HasId + * @property {number | string} id + */ + +/** + * @typedef {function(Module, number): boolean} ModuleFilterPredicate + */ + +/** + * @param {HasId} a first id object to be sorted + * @param {HasId} b second id object to be sorted against + * @returns {-1|0|1} the sort value + */ +const stringifyIdSortPredicate = (a, b) => { + const aId = a.id + ""; + const bId = b.id + ""; + if (aId < bId) return -1; + if (aId > bId) return 1; + return 0; +}; + +class Template { + /** + * + * @param {Function} fn - a runtime function (.runtime.js) "template" + * @returns {string} the updated and normalized function string + */ + static getFunctionContent(fn) { + return fn + .toString() + .replace(FUNCTION_CONTENT_REGEX, "") + .replace(INDENT_MULTILINE_REGEX, "") + .replace(LINE_SEPARATOR_REGEX, "\n"); + } + + /** + * @param {string} str the string converted to identifier + * @returns {string} created identifier + */ + static toIdentifier(str) { + if (typeof str !== "string") return ""; + return str + .replace(IDENTIFIER_NAME_REPLACE_REGEX, "_$1") + .replace(IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX, "_"); + } + /** + * + * @param {string} str string to be converted to commented in bundle code + * @returns {string} returns a commented version of string + */ + static toComment(str) { + if (!str) return ""; + return `/*! ${str.replace(COMMENT_END_REGEX, "* /")} */`; + } + + /** + * + * @param {string} str string to be converted to "normal comment" + * @returns {string} returns a commented version of string + */ + static toNormalComment(str) { + if (!str) return ""; + return `/* ${str.replace(COMMENT_END_REGEX, "* /")} */`; + } + + /** + * @param {string} str string path to be normalized + * @returns {string} normalized bundle-safe path + */ + static toPath(str) { + if (typeof str !== "string") return ""; + return str + .replace(PATH_NAME_NORMALIZE_REPLACE_REGEX, "-") + .replace(MATCH_PADDED_HYPHENS_REPLACE_REGEX, ""); + } + + // map number to a single character a-z, A-Z or <_ + number> if number is too big + /** + * + * @param {number} n number to convert to ident + * @returns {string} returns single character ident + */ + static numberToIdentifer(n) { + // lower case + if (n < DELTA_A_TO_Z) { + return String.fromCharCode(START_LOWERCASE_ALPHABET_CODE + n); + } + + // upper case + if (n < DELTA_A_TO_Z * 2) { + return String.fromCharCode( + START_UPPERCASE_ALPHABET_CODE + n - DELTA_A_TO_Z + ); + } + + // use multiple letters + return ( + Template.numberToIdentifer(n % (2 * DELTA_A_TO_Z)) + + Template.numberToIdentifer(Math.floor(n / (2 * DELTA_A_TO_Z))) + ); + } + + /** + * + * @param {string | string[]} s string to convert to identity + * @returns {string} converted identity + */ + static indent(s) { + if (Array.isArray(s)) { + return s.map(Template.indent).join("\n"); + } else { + const str = s.trimRight(); + if (!str) return ""; + const ind = str[0] === "\n" ? "" : "\t"; + return ind + str.replace(/\n([^\n])/g, "\n\t$1"); + } + } + + /** + * + * @param {string|string[]} s string to create prefix for + * @param {string} prefix prefix to compose + * @returns {string} returns new prefix string + */ + static prefix(s, prefix) { + const str = Template.asString(s).trim(); + if (!str) return ""; + const ind = str[0] === "\n" ? "" : prefix; + return ind + str.replace(/\n([^\n])/g, "\n" + prefix + "$1"); + } + + /** + * + * @param {string|string[]} str string or string collection + * @returns {string} returns a single string from array + */ + static asString(str) { + if (Array.isArray(str)) { + return str.join("\n"); + } + return str; + } + + /** + * @typedef {Object} WithId + * @property {string|number} id + */ + + /** + * @param {WithId[]} modules a collection of modules to get array bounds for + * @returns {[number, number] | false} returns the upper and lower array bounds + * or false if not every module has a number based id + */ + static getModulesArrayBounds(modules) { + let maxId = -Infinity; + let minId = Infinity; + for (const module of modules) { + if (typeof module.id !== "number") return false; + if (maxId < module.id) maxId = /** @type {number} */ (module.id); + if (minId > module.id) minId = /** @type {number} */ (module.id); + } + if (minId < 16 + ("" + minId).length) { + // add minId x ',' instead of 'Array(minId).concat(…)' + minId = 0; + } + const objectOverhead = modules + .map(module => (module.id + "").length + 2) + .reduce((a, b) => a + b, -1); + const arrayOverhead = + minId === 0 ? maxId : 16 + ("" + minId).length + maxId; + return arrayOverhead < objectOverhead ? [minId, maxId] : false; + } + + /** + * @param {Chunk} chunk chunk whose modules will be rendered + * @param {ModuleFilterPredicate} filterFn function used to filter modules from chunk to render + * @param {ModuleTemplate} moduleTemplate ModuleTemplate instance used to render modules + * @param {TODO | TODO[]} dependencyTemplates templates needed for each module to render dependencies + * @param {string=} prefix applying prefix strings + * @returns {ConcatSource} rendered chunk modules in a Source object + */ + static renderChunkModules( + chunk, + filterFn, + moduleTemplate, + dependencyTemplates, + prefix = "" + ) { + const source = new ConcatSource(); + const modules = chunk.getModules().filter(filterFn); + let removedModules; + if (chunk instanceof HotUpdateChunk) { + removedModules = chunk.removedModules; + } + if ( + modules.length === 0 && + (!removedModules || removedModules.length === 0) + ) { + source.add("[]"); + return source; + } + /** @type {{id: string|number, source: Source|string}[]} */ + const allModules = modules.map(module => { + return { + id: module.id, + source: moduleTemplate.render(module, dependencyTemplates, { + chunk + }) + }; + }); + if (removedModules && removedModules.length > 0) { + for (const id of removedModules) { + allModules.push({ + id, + source: "false" + }); + } + } + const bounds = Template.getModulesArrayBounds(allModules); + if (bounds) { + // Render a spare array + const minId = bounds[0]; + const maxId = bounds[1]; + if (minId !== 0) { + source.add(`Array(${minId}).concat(`); + } + source.add("[\n"); + const modules = new Map(); + for (const module of allModules) { + modules.set(module.id, module); + } + for (let idx = minId; idx <= maxId; idx++) { + const module = modules.get(idx); + if (idx !== minId) { + source.add(",\n"); + } + source.add(`/* ${idx} */`); + if (module) { + source.add("\n"); + source.add(module.source); + } + } + source.add("\n" + prefix + "]"); + if (minId !== 0) { + source.add(")"); + } + } else { + // Render an object + source.add("{\n"); + allModules.sort(stringifyIdSortPredicate).forEach((module, idx) => { + if (idx !== 0) { + source.add(",\n"); + } + source.add(`\n/***/ ${JSON.stringify(module.id)}:\n`); + source.add(module.source); + }); + source.add(`\n\n${prefix}}`); + } + return source; + } +} + +module.exports = Template; diff --git a/node_modules/webpack/lib/TemplatedPathPlugin.js b/node_modules/webpack/lib/TemplatedPathPlugin.js index 6c8a2addd..8cd1ef40a 100644 --- a/node_modules/webpack/lib/TemplatedPathPlugin.js +++ b/node_modules/webpack/lib/TemplatedPathPlugin.js @@ -1,112 +1,173 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Jason Anderson @diurnalist
-*/
-"use strict";
-
-const REGEXP_HASH = /\[hash(?::(\d+))?\]/gi,
- REGEXP_CHUNKHASH = /\[chunkhash(?::(\d+))?\]/gi,
- REGEXP_NAME = /\[name\]/gi,
- REGEXP_ID = /\[id\]/gi,
- REGEXP_FILE = /\[file\]/gi,
- REGEXP_QUERY = /\[query\]/gi,
- REGEXP_FILEBASE = /\[filebase\]/gi;
-
-// Using global RegExp for .test is dangerous
-// We use a normal RegExp instead of .test
-const REGEXP_HASH_FOR_TEST = new RegExp(REGEXP_HASH.source, "i"),
- REGEXP_CHUNKHASH_FOR_TEST = new RegExp(REGEXP_CHUNKHASH.source, "i"),
- REGEXP_NAME_FOR_TEST = new RegExp(REGEXP_NAME.source, "i");
-
-// TODO: remove in webpack 3
-// Backwards compatibility; expose regexes on Template object
-const Template = require("./Template");
-Template.REGEXP_HASH = REGEXP_HASH;
-Template.REGEXP_CHUNKHASH = REGEXP_CHUNKHASH;
-Template.REGEXP_NAME = REGEXP_NAME;
-Template.REGEXP_ID = REGEXP_ID;
-Template.REGEXP_FILE = REGEXP_FILE;
-Template.REGEXP_QUERY = REGEXP_QUERY;
-Template.REGEXP_FILEBASE = REGEXP_FILEBASE;
-
-const withHashLength = (replacer, handlerFn) => {
- return function(_, hashLength) {
- const length = hashLength && parseInt(hashLength, 10);
- if(length && handlerFn) {
- return handlerFn(length);
- }
- const hash = replacer.apply(this, arguments);
- return length ? hash.slice(0, length) : hash;
- };
-};
-
-const getReplacer = (value, allowEmpty) => {
- return function(match) {
- // last argument in replacer is the entire input string
- const input = arguments[arguments.length - 1];
- if(value === null || value === undefined) {
- if(!allowEmpty) throw new Error(`Path variable ${match} not implemented in this context: ${input}`);
- return "";
- } else {
- return `${value}`;
- }
- };
-};
-
-const replacePathVariables = (path, data) => {
- const chunk = data.chunk;
- const chunkId = chunk && chunk.id;
- const chunkName = chunk && (chunk.name || chunk.id);
- const chunkHash = chunk && (chunk.renderedHash || chunk.hash);
- const chunkHashWithLength = chunk && chunk.hashWithLength;
-
- if(data.noChunkHash && REGEXP_CHUNKHASH_FOR_TEST.test(path)) {
- throw new Error(`Cannot use [chunkhash] for chunk in '${path}' (use [hash] instead)`);
- }
-
- return path
- .replace(REGEXP_HASH, withHashLength(getReplacer(data.hash), data.hashWithLength))
- .replace(REGEXP_CHUNKHASH, withHashLength(getReplacer(chunkHash), chunkHashWithLength))
- .replace(REGEXP_ID, getReplacer(chunkId))
- .replace(REGEXP_NAME, getReplacer(chunkName))
- .replace(REGEXP_FILE, getReplacer(data.filename))
- .replace(REGEXP_FILEBASE, getReplacer(data.basename))
- // query is optional, it's OK if it's in a path but there's nothing to replace it with
- .replace(REGEXP_QUERY, getReplacer(data.query, true));
-};
-
-class TemplatedPathPlugin {
- apply(compiler) {
- compiler.plugin("compilation", compilation => {
- const mainTemplate = compilation.mainTemplate;
-
- mainTemplate.plugin("asset-path", replacePathVariables);
-
- mainTemplate.plugin("global-hash", function(chunk, paths) {
- const outputOptions = this.outputOptions;
- const publicPath = outputOptions.publicPath || "";
- const filename = outputOptions.filename || "";
- const chunkFilename = outputOptions.chunkFilename || outputOptions.filename;
- if(REGEXP_HASH_FOR_TEST.test(publicPath) || REGEXP_CHUNKHASH_FOR_TEST.test(publicPath) || REGEXP_NAME_FOR_TEST.test(publicPath))
- return true;
- if(REGEXP_HASH_FOR_TEST.test(filename))
- return true;
- if(REGEXP_HASH_FOR_TEST.test(chunkFilename))
- return true;
- if(REGEXP_HASH_FOR_TEST.test(paths.join("|")))
- return true;
- });
-
- mainTemplate.plugin("hash-for-chunk", function(hash, chunk) {
- const outputOptions = this.outputOptions;
- const chunkFilename = outputOptions.chunkFilename || outputOptions.filename;
- if(REGEXP_CHUNKHASH_FOR_TEST.test(chunkFilename))
- hash.update(JSON.stringify(chunk.getChunkMaps(true, true).hash));
- if(REGEXP_NAME_FOR_TEST.test(chunkFilename))
- hash.update(JSON.stringify(chunk.getChunkMaps(true, true).name));
- });
- });
- }
-}
-
-module.exports = TemplatedPathPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Jason Anderson @diurnalist +*/ +"use strict"; + +const REGEXP_HASH = /\[hash(?::(\d+))?\]/gi, + REGEXP_CHUNKHASH = /\[chunkhash(?::(\d+))?\]/gi, + REGEXP_MODULEHASH = /\[modulehash(?::(\d+))?\]/gi, + REGEXP_CONTENTHASH = /\[contenthash(?::(\d+))?\]/gi, + REGEXP_NAME = /\[name\]/gi, + REGEXP_ID = /\[id\]/gi, + REGEXP_MODULEID = /\[moduleid\]/gi, + REGEXP_FILE = /\[file\]/gi, + REGEXP_QUERY = /\[query\]/gi, + REGEXP_FILEBASE = /\[filebase\]/gi; + +// Using global RegExp for .test is dangerous +// We use a normal RegExp instead of .test +const REGEXP_HASH_FOR_TEST = new RegExp(REGEXP_HASH.source, "i"), + REGEXP_CHUNKHASH_FOR_TEST = new RegExp(REGEXP_CHUNKHASH.source, "i"), + REGEXP_CONTENTHASH_FOR_TEST = new RegExp(REGEXP_CONTENTHASH.source, "i"), + REGEXP_NAME_FOR_TEST = new RegExp(REGEXP_NAME.source, "i"); + +const withHashLength = (replacer, handlerFn) => { + const fn = (match, hashLength, ...args) => { + const length = hashLength && parseInt(hashLength, 10); + if (length && handlerFn) { + return handlerFn(length); + } + const hash = replacer(match, hashLength, ...args); + return length ? hash.slice(0, length) : hash; + }; + return fn; +}; + +const getReplacer = (value, allowEmpty) => { + const fn = (match, ...args) => { + // last argument in replacer is the entire input string + const input = args[args.length - 1]; + if (value === null || value === undefined) { + if (!allowEmpty) { + throw new Error( + `Path variable ${match} not implemented in this context: ${input}` + ); + } + return ""; + } else { + return `${value}`; + } + }; + return fn; +}; + +const replacePathVariables = (path, data) => { + const chunk = data.chunk; + const chunkId = chunk && chunk.id; + const chunkName = chunk && (chunk.name || chunk.id); + const chunkHash = chunk && (chunk.renderedHash || chunk.hash); + const chunkHashWithLength = chunk && chunk.hashWithLength; + const contentHashType = data.contentHashType; + const contentHash = + (chunk && chunk.contentHash && chunk.contentHash[contentHashType]) || + data.contentHash; + const contentHashWithLength = + (chunk && + chunk.contentHashWithLength && + chunk.contentHashWithLength[contentHashType]) || + data.contentHashWithLength; + const module = data.module; + const moduleId = module && module.id; + const moduleHash = module && (module.renderedHash || module.hash); + const moduleHashWithLength = module && module.hashWithLength; + + if (typeof path === "function") { + path = path(data); + } + + if ( + data.noChunkHash && + (REGEXP_CHUNKHASH_FOR_TEST.test(path) || + REGEXP_CONTENTHASH_FOR_TEST.test(path)) + ) { + throw new Error( + `Cannot use [chunkhash] or [contenthash] for chunk in '${path}' (use [hash] instead)` + ); + } + + return ( + path + .replace( + REGEXP_HASH, + withHashLength(getReplacer(data.hash), data.hashWithLength) + ) + .replace( + REGEXP_CHUNKHASH, + withHashLength(getReplacer(chunkHash), chunkHashWithLength) + ) + .replace( + REGEXP_CONTENTHASH, + withHashLength(getReplacer(contentHash), contentHashWithLength) + ) + .replace( + REGEXP_MODULEHASH, + withHashLength(getReplacer(moduleHash), moduleHashWithLength) + ) + .replace(REGEXP_ID, getReplacer(chunkId)) + .replace(REGEXP_MODULEID, getReplacer(moduleId)) + .replace(REGEXP_NAME, getReplacer(chunkName)) + .replace(REGEXP_FILE, getReplacer(data.filename)) + .replace(REGEXP_FILEBASE, getReplacer(data.basename)) + // query is optional, it's OK if it's in a path but there's nothing to replace it with + .replace(REGEXP_QUERY, getReplacer(data.query, true)) + ); +}; + +class TemplatedPathPlugin { + apply(compiler) { + compiler.hooks.compilation.tap("TemplatedPathPlugin", compilation => { + const mainTemplate = compilation.mainTemplate; + + mainTemplate.hooks.assetPath.tap( + "TemplatedPathPlugin", + replacePathVariables + ); + + mainTemplate.hooks.globalHash.tap( + "TemplatedPathPlugin", + (chunk, paths) => { + const outputOptions = mainTemplate.outputOptions; + const publicPath = outputOptions.publicPath || ""; + const filename = outputOptions.filename || ""; + const chunkFilename = + outputOptions.chunkFilename || outputOptions.filename; + if ( + REGEXP_HASH_FOR_TEST.test(publicPath) || + REGEXP_CHUNKHASH_FOR_TEST.test(publicPath) || + REGEXP_CONTENTHASH_FOR_TEST.test(publicPath) || + REGEXP_NAME_FOR_TEST.test(publicPath) + ) + return true; + if (REGEXP_HASH_FOR_TEST.test(filename)) return true; + if (REGEXP_HASH_FOR_TEST.test(chunkFilename)) return true; + if (REGEXP_HASH_FOR_TEST.test(paths.join("|"))) return true; + } + ); + + mainTemplate.hooks.hashForChunk.tap( + "TemplatedPathPlugin", + (hash, chunk) => { + const outputOptions = mainTemplate.outputOptions; + const chunkFilename = + outputOptions.chunkFilename || outputOptions.filename; + if (REGEXP_CHUNKHASH_FOR_TEST.test(chunkFilename)) { + hash.update(JSON.stringify(chunk.getChunkMaps(true).hash)); + } + if (REGEXP_CONTENTHASH_FOR_TEST.test(chunkFilename)) { + hash.update( + JSON.stringify( + chunk.getChunkMaps(true).contentHash.javascript || {} + ) + ); + } + if (REGEXP_NAME_FOR_TEST.test(chunkFilename)) { + hash.update(JSON.stringify(chunk.getChunkMaps(true).name)); + } + } + ); + }); + } +} + +module.exports = TemplatedPathPlugin; diff --git a/node_modules/webpack/lib/UmdMainTemplatePlugin.js b/node_modules/webpack/lib/UmdMainTemplatePlugin.js index cc5179692..551ac76f8 100644 --- a/node_modules/webpack/lib/UmdMainTemplatePlugin.js +++ b/node_modules/webpack/lib/UmdMainTemplatePlugin.js @@ -1,191 +1,304 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const ConcatSource = require("webpack-sources").ConcatSource;
-const OriginalSource = require("webpack-sources").OriginalSource;
-const Template = require("./Template");
-
-function accessorToObjectAccess(accessor) {
- return accessor.map(a => `[${JSON.stringify(a)}]`).join("");
-}
-
-function accessorAccess(base, accessor) {
- accessor = [].concat(accessor);
- return accessor.map((a, idx) => {
- a = base + accessorToObjectAccess(accessor.slice(0, idx + 1));
- if(idx === accessor.length - 1) return a;
- return `${a} = ${a} || {}`;
- }).join(", ");
-}
-
-class UmdMainTemplatePlugin {
- constructor(name, options) {
- if(typeof name === "object" && !Array.isArray(name)) {
- this.name = name.root || name.amd || name.commonjs;
- this.names = name;
- } else {
- this.name = name;
- this.names = {
- commonjs: name,
- root: name,
- amd: name
- };
- }
- this.optionalAmdExternalAsGlobal = options.optionalAmdExternalAsGlobal;
- this.namedDefine = options.namedDefine;
- this.auxiliaryComment = options.auxiliaryComment;
- }
-
- apply(compilation) {
- const mainTemplate = compilation.mainTemplate;
- compilation.templatesPlugin("render-with-entry", (source, chunk, hash) => {
- let externals = chunk.getModules().filter(m => m.external && (m.type === "umd" || m.type === "umd2"));
- const optionalExternals = [];
- let requiredExternals = [];
- if(this.optionalAmdExternalAsGlobal) {
- externals.forEach(m => {
- if(m.optional) {
- optionalExternals.push(m);
- } else {
- requiredExternals.push(m);
- }
- });
- externals = requiredExternals.concat(optionalExternals);
- } else {
- requiredExternals = externals;
- }
-
- function replaceKeys(str) {
- return mainTemplate.applyPluginsWaterfall("asset-path", str, {
- hash,
- chunk
- });
- }
-
- function externalsDepsArray(modules) {
- return `[${replaceKeys(modules.map(m => JSON.stringify(typeof m.request === "object" ? m.request.amd : m.request)).join(", "))}]`;
- }
-
- function externalsRootArray(modules) {
- return replaceKeys(modules.map(m => {
- let request = m.request;
- if(typeof request === "object") request = request.root;
- return `root${accessorToObjectAccess([].concat(request))}`;
- }).join(", "));
- }
-
- function externalsRequireArray(type) {
- return replaceKeys(externals.map(m => {
- let expr;
- let request = m.request;
- if(typeof request === "object") request = request[type];
- if(typeof request === "undefined") throw new Error("Missing external configuration for type:" + type);
- if(Array.isArray(request)) {
- expr = `require(${JSON.stringify(request[0])})${accessorToObjectAccess(request.slice(1))}`;
- } else
- expr = `require(${JSON.stringify(request)})`;
- if(m.optional) {
- expr = `(function webpackLoadOptionalExternalModule() { try { return ${expr}; } catch(e) {} }())`;
- }
- return expr;
- }).join(", "));
- }
-
- function externalsArguments(modules) {
- return modules.map(m => Template.toIdentifier(`__WEBPACK_EXTERNAL_MODULE_${m.id}__`)).join(", ");
- }
-
- function libraryName(library) {
- return JSON.stringify(replaceKeys([].concat(library).pop()));
- }
-
- let amdFactory;
- if(optionalExternals.length > 0) {
- const wrapperArguments = externalsArguments(requiredExternals);
- const factoryArguments = requiredExternals.length > 0 ?
- externalsArguments(requiredExternals) + ", " + externalsRootArray(optionalExternals) :
- externalsRootArray(optionalExternals);
- amdFactory = `function webpackLoadOptionalExternalModuleAmd(${wrapperArguments}) {\n` +
- ` return factory(${factoryArguments});\n` +
- " }";
- } else {
- amdFactory = "factory";
- }
-
- return new ConcatSource(new OriginalSource(
- "(function webpackUniversalModuleDefinition(root, factory) {\n" +
- (this.auxiliaryComment &&
- typeof this.auxiliaryComment === "string" ?
- " //" + this.auxiliaryComment + "\n" :
- this.auxiliaryComment.commonjs2 ?
- " //" + this.auxiliaryComment.commonjs2 + "\n" :
- ""
- ) +
- " if(typeof exports === 'object' && typeof module === 'object')\n" +
- " module.exports = factory(" + externalsRequireArray("commonjs2") + ");\n" +
- (this.auxiliaryComment &&
- typeof this.auxiliaryComment === "string" ?
- " //" + this.auxiliaryComment + "\n" :
- this.auxiliaryComment.amd ?
- " //" + this.auxiliaryComment.amd + "\n" :
- ""
- ) +
- " else if(typeof define === 'function' && define.amd)\n" +
- (requiredExternals.length > 0 ?
- (this.names.amd && this.namedDefine === true ?
- " define(" + libraryName(this.names.amd) + ", " + externalsDepsArray(requiredExternals) + ", " + amdFactory + ");\n" :
- " define(" + externalsDepsArray(requiredExternals) + ", " + amdFactory + ");\n"
- ) :
- (this.names.amd && this.namedDefine === true ?
- " define(" + libraryName(this.names.amd) + ", [], " + amdFactory + ");\n" :
- " define([], " + amdFactory + ");\n"
- )
- ) +
- (this.names.root || this.names.commonjs ?
- (this.auxiliaryComment &&
- typeof this.auxiliaryComment === "string" ?
- " //" + this.auxiliaryComment + "\n" :
- this.auxiliaryComment.commonjs ?
- " //" + this.auxiliaryComment.commonjs + "\n" :
- ""
- ) +
- " else if(typeof exports === 'object')\n" +
- " exports[" + libraryName(this.names.commonjs || this.names.root) + "] = factory(" + externalsRequireArray("commonjs") + ");\n" +
- (this.auxiliaryComment &&
- typeof this.auxiliaryComment === "string" ?
- " //" + this.auxiliaryComment + "\n" :
- this.auxiliaryComment.root ?
- " //" + this.auxiliaryComment.root + "\n" :
- ""
- ) +
- " else\n" +
- " " + replaceKeys(accessorAccess("root", this.names.root || this.names.commonjs)) + " = factory(" + externalsRootArray(externals) + ");\n" :
- " else {\n" +
- (externals.length > 0 ?
- " var a = typeof exports === 'object' ? factory(" + externalsRequireArray("commonjs") + ") : factory(" + externalsRootArray(externals) + ");\n" :
- " var a = factory();\n"
- ) +
- " for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n" +
- " }\n"
- ) +
- "})(typeof self !== 'undefined' ? self : this, function(" + externalsArguments(externals) + ") {\nreturn ", "webpack/universalModuleDefinition"), source, ";\n})");
- });
- mainTemplate.plugin("global-hash-paths", (paths) => {
- if(this.names.root) paths = paths.concat(this.names.root);
- if(this.names.amd) paths = paths.concat(this.names.amd);
- if(this.names.commonjs) paths = paths.concat(this.names.commonjs);
- return paths;
- });
- mainTemplate.plugin("hash", (hash) => {
- hash.update("umd");
- hash.update(`${this.names.root}`);
- hash.update(`${this.names.amd}`);
- hash.update(`${this.names.commonjs}`);
- });
- }
-}
-
-module.exports = UmdMainTemplatePlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const { ConcatSource, OriginalSource } = require("webpack-sources"); +const Template = require("./Template"); + +/** @typedef {import("./Compilation")} Compilation */ + +/** + * @param {string[]} accessor the accessor to convert to path + * @returns {string} the path + */ +const accessorToObjectAccess = accessor => { + return accessor.map(a => `[${JSON.stringify(a)}]`).join(""); +}; + +/** + * @param {string=} base the path prefix + * @param {string|string[]} accessor the accessor + * @param {string=} joinWith the element separator + * @returns {string} the path + */ +const accessorAccess = (base, accessor, joinWith = ", ") => { + const accessors = Array.isArray(accessor) ? accessor : [accessor]; + return accessors + .map((_, idx) => { + const a = base + ? base + accessorToObjectAccess(accessors.slice(0, idx + 1)) + : accessors[0] + accessorToObjectAccess(accessors.slice(1, idx + 1)); + if (idx === accessors.length - 1) return a; + if (idx === 0 && base === undefined) + return `${a} = typeof ${a} === "object" ? ${a} : {}`; + return `${a} = ${a} || {}`; + }) + .join(joinWith); +}; + +/** @typedef {string | string[] | Record<string, string | string[]>} UmdMainTemplatePluginName */ + +/** + * @typedef {Object} AuxiliaryCommentObject + * @property {string} root + * @property {string} commonjs + * @property {string} commonjs2 + * @property {string} amd + */ + +/** + * @typedef {Object} UmdMainTemplatePluginOption + * @property {boolean=} optionalAmdExternalAsGlobal + * @property {boolean} namedDefine + * @property {string | AuxiliaryCommentObject} auxiliaryComment + */ + +class UmdMainTemplatePlugin { + /** + * @param {UmdMainTemplatePluginName} name the name of the UMD library + * @param {UmdMainTemplatePluginOption} options the plugin option + */ + constructor(name, options) { + if (typeof name === "object" && !Array.isArray(name)) { + this.name = name.root || name.amd || name.commonjs; + this.names = name; + } else { + this.name = name; + this.names = { + commonjs: name, + root: name, + amd: name + }; + } + this.optionalAmdExternalAsGlobal = options.optionalAmdExternalAsGlobal; + this.namedDefine = options.namedDefine; + this.auxiliaryComment = options.auxiliaryComment; + } + + /** + * @param {Compilation} compilation the compilation instance + * @returns {void} + */ + apply(compilation) { + const { mainTemplate, chunkTemplate, runtimeTemplate } = compilation; + + const onRenderWithEntry = (source, chunk, hash) => { + let externals = chunk + .getModules() + .filter( + m => + m.external && + (m.externalType === "umd" || m.externalType === "umd2") + ); + const optionalExternals = []; + let requiredExternals = []; + if (this.optionalAmdExternalAsGlobal) { + for (const m of externals) { + if (m.optional) { + optionalExternals.push(m); + } else { + requiredExternals.push(m); + } + } + externals = requiredExternals.concat(optionalExternals); + } else { + requiredExternals = externals; + } + + const replaceKeys = str => { + return mainTemplate.getAssetPath(str, { + hash, + chunk + }); + }; + + const externalsDepsArray = modules => { + return `[${replaceKeys( + modules + .map(m => + JSON.stringify( + typeof m.request === "object" ? m.request.amd : m.request + ) + ) + .join(", ") + )}]`; + }; + + const externalsRootArray = modules => { + return replaceKeys( + modules + .map(m => { + let request = m.request; + if (typeof request === "object") request = request.root; + return `root${accessorToObjectAccess([].concat(request))}`; + }) + .join(", ") + ); + }; + + const externalsRequireArray = type => { + return replaceKeys( + externals + .map(m => { + let expr; + let request = m.request; + if (typeof request === "object") { + request = request[type]; + } + if (request === undefined) { + throw new Error( + "Missing external configuration for type:" + type + ); + } + if (Array.isArray(request)) { + expr = `require(${JSON.stringify( + request[0] + )})${accessorToObjectAccess(request.slice(1))}`; + } else { + expr = `require(${JSON.stringify(request)})`; + } + if (m.optional) { + expr = `(function webpackLoadOptionalExternalModule() { try { return ${expr}; } catch(e) {} }())`; + } + return expr; + }) + .join(", ") + ); + }; + + const externalsArguments = modules => { + return modules + .map( + m => + `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier(`${m.id}`)}__` + ) + .join(", "); + }; + + const libraryName = library => { + return JSON.stringify(replaceKeys([].concat(library).pop())); + }; + + let amdFactory; + if (optionalExternals.length > 0) { + const wrapperArguments = externalsArguments(requiredExternals); + const factoryArguments = + requiredExternals.length > 0 + ? externalsArguments(requiredExternals) + + ", " + + externalsRootArray(optionalExternals) + : externalsRootArray(optionalExternals); + amdFactory = + `function webpackLoadOptionalExternalModuleAmd(${wrapperArguments}) {\n` + + ` return factory(${factoryArguments});\n` + + " }"; + } else { + amdFactory = "factory"; + } + + const auxiliaryComment = this.auxiliaryComment; + + const getAuxilaryComment = type => { + if (auxiliaryComment) { + if (typeof auxiliaryComment === "string") + return "\t//" + auxiliaryComment + "\n"; + if (auxiliaryComment[type]) + return "\t//" + auxiliaryComment[type] + "\n"; + } + return ""; + }; + + return new ConcatSource( + new OriginalSource( + "(function webpackUniversalModuleDefinition(root, factory) {\n" + + getAuxilaryComment("commonjs2") + + " if(typeof exports === 'object' && typeof module === 'object')\n" + + " module.exports = factory(" + + externalsRequireArray("commonjs2") + + ");\n" + + getAuxilaryComment("amd") + + " else if(typeof define === 'function' && define.amd)\n" + + (requiredExternals.length > 0 + ? this.names.amd && this.namedDefine === true + ? " define(" + + libraryName(this.names.amd) + + ", " + + externalsDepsArray(requiredExternals) + + ", " + + amdFactory + + ");\n" + : " define(" + + externalsDepsArray(requiredExternals) + + ", " + + amdFactory + + ");\n" + : this.names.amd && this.namedDefine === true + ? " define(" + + libraryName(this.names.amd) + + ", [], " + + amdFactory + + ");\n" + : " define([], " + amdFactory + ");\n") + + (this.names.root || this.names.commonjs + ? getAuxilaryComment("commonjs") + + " else if(typeof exports === 'object')\n" + + " exports[" + + libraryName(this.names.commonjs || this.names.root) + + "] = factory(" + + externalsRequireArray("commonjs") + + ");\n" + + getAuxilaryComment("root") + + " else\n" + + " " + + replaceKeys( + accessorAccess("root", this.names.root || this.names.commonjs) + ) + + " = factory(" + + externalsRootArray(externals) + + ");\n" + : " else {\n" + + (externals.length > 0 + ? " var a = typeof exports === 'object' ? factory(" + + externalsRequireArray("commonjs") + + ") : factory(" + + externalsRootArray(externals) + + ");\n" + : " var a = factory();\n") + + " for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n" + + " }\n") + + `})(${ + runtimeTemplate.outputOptions.globalObject + }, function(${externalsArguments(externals)}) {\nreturn `, + "webpack/universalModuleDefinition" + ), + source, + ";\n})" + ); + }; + + for (const template of [mainTemplate, chunkTemplate]) { + template.hooks.renderWithEntry.tap( + "UmdMainTemplatePlugin", + onRenderWithEntry + ); + } + + mainTemplate.hooks.globalHashPaths.tap("UmdMainTemplatePlugin", paths => { + if (this.names.root) paths = paths.concat(this.names.root); + if (this.names.amd) paths = paths.concat(this.names.amd); + if (this.names.commonjs) paths = paths.concat(this.names.commonjs); + return paths; + }); + + mainTemplate.hooks.hash.tap("UmdMainTemplatePlugin", hash => { + hash.update("umd"); + hash.update(`${this.names.root}`); + hash.update(`${this.names.amd}`); + hash.update(`${this.names.commonjs}`); + }); + } +} + +module.exports = UmdMainTemplatePlugin; diff --git a/node_modules/webpack/lib/UnsupportedFeatureWarning.js b/node_modules/webpack/lib/UnsupportedFeatureWarning.js index d2b270336..72eef834e 100644 --- a/node_modules/webpack/lib/UnsupportedFeatureWarning.js +++ b/node_modules/webpack/lib/UnsupportedFeatureWarning.js @@ -1,21 +1,30 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const WebpackError = require("./WebpackError");
-
-class UnsupportedFeatureWarning extends WebpackError {
- constructor(module, message) {
- super();
-
- this.name = "UnsupportedFeatureWarning";
- this.message = message;
- this.origin = this.module = module;
-
- Error.captureStackTrace(this, this.constructor);
- }
-}
-
-module.exports = UnsupportedFeatureWarning;
+/* + 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("./Dependency").DependencyLocation} DependencyLocation */ + +class UnsupportedFeatureWarning extends WebpackError { + /** + * @param {Module} module module relevant to warning + * @param {string} message description of warning + * @param {DependencyLocation} loc location start and end positions of the module + */ + constructor(module, message, loc) { + super(message); + + this.name = "UnsupportedFeatureWarning"; + this.module = module; + this.loc = loc; + this.hideStack = true; + + Error.captureStackTrace(this, this.constructor); + } +} + +module.exports = UnsupportedFeatureWarning; diff --git a/node_modules/webpack/lib/UseStrictPlugin.js b/node_modules/webpack/lib/UseStrictPlugin.js index 2135839cf..425be2e31 100644 --- a/node_modules/webpack/lib/UseStrictPlugin.js +++ b/node_modules/webpack/lib/UseStrictPlugin.js @@ -1,34 +1,54 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const ConstDependency = require("./dependencies/ConstDependency");
-
-class UseStrictPlugin {
- apply(compiler) {
- compiler.plugin("compilation", (compilation, params) => {
- params.normalModuleFactory.plugin("parser", (parser) => {
- const parserInstance = parser;
- parser.plugin("program", (ast) => {
- const firstNode = ast.body[0];
- if(firstNode &&
- firstNode.type === "ExpressionStatement" &&
- firstNode.expression.type === "Literal" &&
- firstNode.expression.value === "use strict") {
- // Remove "use strict" expression. It will be added later by the renderer again.
- // This is necessary in order to not break the strict mode when webpack prepends code.
- // @see https://github.com/webpack/webpack/issues/1970
- const dep = new ConstDependency("", firstNode.range);
- dep.loc = firstNode.loc;
- parserInstance.state.current.addDependency(dep);
- parserInstance.state.module.strict = true;
- }
- });
- });
- });
- }
-}
-
-module.exports = UseStrictPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const ConstDependency = require("./dependencies/ConstDependency"); + +/** @typedef {import("./Compiler")} Compiler */ + +class UseStrictPlugin { + /** + * @param {Compiler} compiler Webpack Compiler + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "UseStrictPlugin", + (compilation, { normalModuleFactory }) => { + const handler = parser => { + parser.hooks.program.tap("UseStrictPlugin", ast => { + const firstNode = ast.body[0]; + if ( + firstNode && + firstNode.type === "ExpressionStatement" && + firstNode.expression.type === "Literal" && + firstNode.expression.value === "use strict" + ) { + // Remove "use strict" expression. It will be added later by the renderer again. + // This is necessary in order to not break the strict mode when webpack prepends code. + // @see https://github.com/webpack/webpack/issues/1970 + const dep = new ConstDependency("", firstNode.range); + dep.loc = firstNode.loc; + parser.state.current.addDependency(dep); + parser.state.module.buildInfo.strict = true; + } + }); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("UseStrictPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("UseStrictPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("UseStrictPlugin", handler); + } + ); + } +} + +module.exports = UseStrictPlugin; diff --git a/node_modules/webpack/lib/WarnCaseSensitiveModulesPlugin.js b/node_modules/webpack/lib/WarnCaseSensitiveModulesPlugin.js index 54edb4ac7..867a33fe3 100644 --- a/node_modules/webpack/lib/WarnCaseSensitiveModulesPlugin.js +++ b/node_modules/webpack/lib/WarnCaseSensitiveModulesPlugin.js @@ -1,31 +1,37 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const CaseSensitiveModulesWarning = require("./CaseSensitiveModulesWarning");
-
-class WarnCaseSensitiveModulesPlugin {
- apply(compiler) {
- compiler.plugin("compilation", compilation => {
- compilation.plugin("seal", () => {
- const moduleWithoutCase = Object.create(null);
- compilation.modules.forEach(module => {
- const identifier = module.identifier().toLowerCase();
- if(moduleWithoutCase[identifier]) {
- moduleWithoutCase[identifier].push(module);
- } else {
- moduleWithoutCase[identifier] = [module];
- }
- });
- Object.keys(moduleWithoutCase).forEach(key => {
- if(moduleWithoutCase[key].length > 1)
- compilation.warnings.push(new CaseSensitiveModulesWarning(moduleWithoutCase[key]));
- });
- });
- });
- }
-}
-
-module.exports = WarnCaseSensitiveModulesPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const CaseSensitiveModulesWarning = require("./CaseSensitiveModulesWarning"); + +class WarnCaseSensitiveModulesPlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "WarnCaseSensitiveModulesPlugin", + compilation => { + compilation.hooks.seal.tap("WarnCaseSensitiveModulesPlugin", () => { + const moduleWithoutCase = new Map(); + for (const module of compilation.modules) { + const identifier = module.identifier().toLowerCase(); + const array = moduleWithoutCase.get(identifier); + if (array) { + array.push(module); + } else { + moduleWithoutCase.set(identifier, [module]); + } + } + for (const pair of moduleWithoutCase) { + const array = pair[1]; + if (array.length > 1) { + compilation.warnings.push(new CaseSensitiveModulesWarning(array)); + } + } + }); + } + ); + } +} + +module.exports = WarnCaseSensitiveModulesPlugin; diff --git a/node_modules/webpack/lib/WatchIgnorePlugin.js b/node_modules/webpack/lib/WatchIgnorePlugin.js index 9b74b3c20..2f81ee839 100644 --- a/node_modules/webpack/lib/WatchIgnorePlugin.js +++ b/node_modules/webpack/lib/WatchIgnorePlugin.js @@ -1,49 +1,100 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-class WatchIgnorePlugin {
- constructor(paths) {
- this.paths = paths;
- }
-
- apply(compiler) {
- compiler.plugin("after-environment", () => {
- compiler.watchFileSystem = new IgnoringWatchFileSystem(compiler.watchFileSystem, this.paths);
- });
- }
-}
-
-module.exports = WatchIgnorePlugin;
-
-class IgnoringWatchFileSystem {
- constructor(wfs, paths) {
- this.wfs = wfs;
- this.paths = paths;
- }
-
- watch(files, dirs, missing, startTime, options, callback, callbackUndelayed) {
- const ignored = path => this.paths.some(p => p instanceof RegExp ? p.test(path) : path.indexOf(p) === 0);
-
- const notIgnored = path => !ignored(path);
-
- const ignoredFiles = files.filter(ignored);
- const ignoredDirs = dirs.filter(ignored);
-
- this.wfs.watch(files.filter(notIgnored), dirs.filter(notIgnored), missing, startTime, options, (err, filesModified, dirsModified, missingModified, fileTimestamps, dirTimestamps) => {
- if(err) return callback(err);
-
- ignoredFiles.forEach(path => {
- fileTimestamps[path] = 1;
- });
-
- ignoredDirs.forEach(path => {
- dirTimestamps[path] = 1;
- });
-
- callback(err, filesModified, dirsModified, missingModified, fileTimestamps, dirTimestamps);
- }, callbackUndelayed);
- }
-}
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const validateOptions = require("schema-utils"); +const schema = require("../schemas/plugins/WatchIgnorePlugin.json"); + +class IgnoringWatchFileSystem { + constructor(wfs, paths) { + this.wfs = wfs; + this.paths = paths; + } + + watch(files, dirs, missing, startTime, options, callback, callbackUndelayed) { + const ignored = path => + this.paths.some( + p => (p instanceof RegExp ? p.test(path) : path.indexOf(p) === 0) + ); + + const notIgnored = path => !ignored(path); + + const ignoredFiles = files.filter(ignored); + const ignoredDirs = dirs.filter(ignored); + + const watcher = this.wfs.watch( + files.filter(notIgnored), + dirs.filter(notIgnored), + missing, + startTime, + options, + ( + err, + filesModified, + dirsModified, + missingModified, + fileTimestamps, + dirTimestamps + ) => { + if (err) return callback(err); + + for (const path of ignoredFiles) { + fileTimestamps.set(path, 1); + } + + for (const path of ignoredDirs) { + dirTimestamps.set(path, 1); + } + + callback( + err, + filesModified, + dirsModified, + missingModified, + fileTimestamps, + dirTimestamps + ); + }, + callbackUndelayed + ); + + return { + close: () => watcher.close(), + pause: () => watcher.pause(), + getContextTimestamps: () => { + const dirTimestamps = watcher.getContextTimestamps(); + for (const path of ignoredDirs) { + dirTimestamps.set(path, 1); + } + return dirTimestamps; + }, + getFileTimestamps: () => { + const fileTimestamps = watcher.getFileTimestamps(); + for (const path of ignoredFiles) { + fileTimestamps.set(path, 1); + } + return fileTimestamps; + } + }; + } +} + +class WatchIgnorePlugin { + constructor(paths) { + validateOptions(schema, paths, "Watch Ignore Plugin"); + this.paths = paths; + } + + apply(compiler) { + compiler.hooks.afterEnvironment.tap("WatchIgnorePlugin", () => { + compiler.watchFileSystem = new IgnoringWatchFileSystem( + compiler.watchFileSystem, + this.paths + ); + }); + } +} + +module.exports = WatchIgnorePlugin; diff --git a/node_modules/webpack/lib/WebpackError.js b/node_modules/webpack/lib/WebpackError.js index abd716a63..891809a67 100644 --- a/node_modules/webpack/lib/WebpackError.js +++ b/node_modules/webpack/lib/WebpackError.js @@ -1,11 +1,29 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Jarid Margolin @jaridmargolin
-*/
-"use strict";
-
-module.exports = class WebpackError extends Error {
- inspect() {
- return this.stack + (this.details ? `\n${this.details}` : "");
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Jarid Margolin @jaridmargolin +*/ +"use strict"; + +class WebpackError extends Error { + /** + * Creates an instance of WebpackError. + * @param {string=} message error message + */ + constructor(message) { + super(message); + + this.details = undefined; + this.missing = undefined; + this.origin = undefined; + this.dependencies = undefined; + this.module = undefined; + + Error.captureStackTrace(this, this.constructor); + } + + inspect() { + return this.stack + (this.details ? `\n${this.details}` : ""); + } +} + +module.exports = WebpackError; diff --git a/node_modules/webpack/lib/WebpackOptionsApply.js b/node_modules/webpack/lib/WebpackOptionsApply.js index ebddba717..2456a7bd7 100644 --- a/node_modules/webpack/lib/WebpackOptionsApply.js +++ b/node_modules/webpack/lib/WebpackOptionsApply.js @@ -1,298 +1,519 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const OptionsApply = require("./OptionsApply");
-
-const LoaderTargetPlugin = require("./LoaderTargetPlugin");
-const FunctionModulePlugin = require("./FunctionModulePlugin");
-const EvalDevToolModulePlugin = require("./EvalDevToolModulePlugin");
-const SourceMapDevToolPlugin = require("./SourceMapDevToolPlugin");
-const EvalSourceMapDevToolPlugin = require("./EvalSourceMapDevToolPlugin");
-
-const EntryOptionPlugin = require("./EntryOptionPlugin");
-const RecordIdsPlugin = require("./RecordIdsPlugin");
-
-const APIPlugin = require("./APIPlugin");
-const ConstPlugin = require("./ConstPlugin");
-const RequireJsStuffPlugin = require("./RequireJsStuffPlugin");
-const NodeStuffPlugin = require("./NodeStuffPlugin");
-const CompatibilityPlugin = require("./CompatibilityPlugin");
-
-const TemplatedPathPlugin = require("./TemplatedPathPlugin");
-const WarnCaseSensitiveModulesPlugin = require("./WarnCaseSensitiveModulesPlugin");
-const UseStrictPlugin = require("./UseStrictPlugin");
-
-const LoaderPlugin = require("./dependencies/LoaderPlugin");
-const CommonJsPlugin = require("./dependencies/CommonJsPlugin");
-const HarmonyModulesPlugin = require("./dependencies/HarmonyModulesPlugin");
-const SystemPlugin = require("./dependencies/SystemPlugin");
-const ImportPlugin = require("./dependencies/ImportPlugin");
-const AMDPlugin = require("./dependencies/AMDPlugin");
-const RequireContextPlugin = require("./dependencies/RequireContextPlugin");
-const RequireEnsurePlugin = require("./dependencies/RequireEnsurePlugin");
-const RequireIncludePlugin = require("./dependencies/RequireIncludePlugin");
-
-const EnsureChunkConditionsPlugin = require("./optimize/EnsureChunkConditionsPlugin");
-const RemoveParentModulesPlugin = require("./optimize/RemoveParentModulesPlugin");
-const RemoveEmptyChunksPlugin = require("./optimize/RemoveEmptyChunksPlugin");
-const MergeDuplicateChunksPlugin = require("./optimize/MergeDuplicateChunksPlugin");
-const FlagIncludedChunksPlugin = require("./optimize/FlagIncludedChunksPlugin");
-const OccurrenceOrderPlugin = require("./optimize/OccurrenceOrderPlugin");
-const FlagDependencyUsagePlugin = require("./FlagDependencyUsagePlugin");
-const FlagDependencyExportsPlugin = require("./FlagDependencyExportsPlugin");
-const SizeLimitsPlugin = require("./performance/SizeLimitsPlugin");
-
-const ResolverFactory = require("enhanced-resolve").ResolverFactory;
-
-class WebpackOptionsApply extends OptionsApply {
- constructor() {
- super();
- }
-
- process(options, compiler) {
- let ExternalsPlugin;
- compiler.outputPath = options.output.path;
- compiler.recordsInputPath = options.recordsInputPath || options.recordsPath;
- compiler.recordsOutputPath = options.recordsOutputPath || options.recordsPath;
- compiler.name = options.name;
- compiler.dependencies = options.dependencies;
- if(typeof options.target === "string") {
- let JsonpTemplatePlugin;
- let NodeSourcePlugin;
- let NodeTargetPlugin;
- let NodeTemplatePlugin;
-
- switch(options.target) {
- case "web":
- JsonpTemplatePlugin = require("./JsonpTemplatePlugin");
- NodeSourcePlugin = require("./node/NodeSourcePlugin");
- compiler.apply(
- new JsonpTemplatePlugin(options.output),
- new FunctionModulePlugin(options.output),
- new NodeSourcePlugin(options.node),
- new LoaderTargetPlugin(options.target)
- );
- break;
- case "webworker":
- {
- let WebWorkerTemplatePlugin = require("./webworker/WebWorkerTemplatePlugin");
- NodeSourcePlugin = require("./node/NodeSourcePlugin");
- compiler.apply(
- new WebWorkerTemplatePlugin(),
- new FunctionModulePlugin(options.output),
- new NodeSourcePlugin(options.node),
- new LoaderTargetPlugin(options.target)
- );
- break;
- }
- case "node":
- case "async-node":
- NodeTemplatePlugin = require("./node/NodeTemplatePlugin");
- NodeTargetPlugin = require("./node/NodeTargetPlugin");
- compiler.apply(
- new NodeTemplatePlugin({
- asyncChunkLoading: options.target === "async-node"
- }),
- new FunctionModulePlugin(options.output),
- new NodeTargetPlugin(),
- new LoaderTargetPlugin("node")
- );
- break;
- case "node-webkit":
- JsonpTemplatePlugin = require("./JsonpTemplatePlugin");
- NodeTargetPlugin = require("./node/NodeTargetPlugin");
- ExternalsPlugin = require("./ExternalsPlugin");
- compiler.apply(
- new JsonpTemplatePlugin(options.output),
- new FunctionModulePlugin(options.output),
- new NodeTargetPlugin(),
- new ExternalsPlugin("commonjs", "nw.gui"),
- new LoaderTargetPlugin(options.target)
- );
- break;
- case "atom":
- case "electron":
- case "electron-main":
- NodeTemplatePlugin = require("./node/NodeTemplatePlugin");
- NodeTargetPlugin = require("./node/NodeTargetPlugin");
- ExternalsPlugin = require("./ExternalsPlugin");
- compiler.apply(
- new NodeTemplatePlugin({
- asyncChunkLoading: true
- }),
- new FunctionModulePlugin(options.output),
- new NodeTargetPlugin(),
- new ExternalsPlugin("commonjs", [
- "app",
- "auto-updater",
- "browser-window",
- "content-tracing",
- "dialog",
- "electron",
- "global-shortcut",
- "ipc",
- "ipc-main",
- "menu",
- "menu-item",
- "power-monitor",
- "power-save-blocker",
- "protocol",
- "session",
- "web-contents",
- "tray",
- "clipboard",
- "crash-reporter",
- "native-image",
- "screen",
- "shell"
- ]),
- new LoaderTargetPlugin(options.target)
- );
- break;
- case "electron-renderer":
- JsonpTemplatePlugin = require("./JsonpTemplatePlugin");
- NodeTargetPlugin = require("./node/NodeTargetPlugin");
- ExternalsPlugin = require("./ExternalsPlugin");
- compiler.apply(
- new JsonpTemplatePlugin(options.output),
- new FunctionModulePlugin(options.output),
- new NodeTargetPlugin(),
- new ExternalsPlugin("commonjs", [
- "desktop-capturer",
- "electron",
- "ipc",
- "ipc-renderer",
- "remote",
- "web-frame",
- "clipboard",
- "crash-reporter",
- "native-image",
- "screen",
- "shell"
- ]),
- new LoaderTargetPlugin(options.target)
- );
- break;
- default:
- throw new Error("Unsupported target '" + options.target + "'.");
- }
- } else if(options.target !== false) {
- options.target(compiler);
- } else {
- throw new Error("Unsupported target '" + options.target + "'.");
- }
-
- if(options.output.library || options.output.libraryTarget !== "var") {
- let LibraryTemplatePlugin = require("./LibraryTemplatePlugin");
- compiler.apply(new LibraryTemplatePlugin(options.output.library, options.output.libraryTarget, options.output.umdNamedDefine, options.output.auxiliaryComment || "", options.output.libraryExport));
- }
- if(options.externals) {
- ExternalsPlugin = require("./ExternalsPlugin");
- compiler.apply(new ExternalsPlugin(options.output.libraryTarget, options.externals));
- }
- let noSources;
- let legacy;
- let modern;
- let comment;
- if(options.devtool && (options.devtool.indexOf("sourcemap") >= 0 || options.devtool.indexOf("source-map") >= 0)) {
- const hidden = options.devtool.indexOf("hidden") >= 0;
- const inline = options.devtool.indexOf("inline") >= 0;
- const evalWrapped = options.devtool.indexOf("eval") >= 0;
- const cheap = options.devtool.indexOf("cheap") >= 0;
- const moduleMaps = options.devtool.indexOf("module") >= 0;
- noSources = options.devtool.indexOf("nosources") >= 0;
- legacy = options.devtool.indexOf("@") >= 0;
- modern = options.devtool.indexOf("#") >= 0;
- comment = legacy && modern ? "\n/*\n//@ source" + "MappingURL=[url]\n//# source" + "MappingURL=[url]\n*/" :
- legacy ? "\n/*\n//@ source" + "MappingURL=[url]\n*/" :
- modern ? "\n//# source" + "MappingURL=[url]" :
- null;
- let Plugin = evalWrapped ? EvalSourceMapDevToolPlugin : SourceMapDevToolPlugin;
- compiler.apply(new Plugin({
- filename: inline ? null : options.output.sourceMapFilename,
- moduleFilenameTemplate: options.output.devtoolModuleFilenameTemplate,
- fallbackModuleFilenameTemplate: options.output.devtoolFallbackModuleFilenameTemplate,
- append: hidden ? false : comment,
- module: moduleMaps ? true : cheap ? false : true,
- columns: cheap ? false : true,
- lineToLine: options.output.devtoolLineToLine,
- noSources: noSources,
- }));
- } else if(options.devtool && options.devtool.indexOf("eval") >= 0) {
- legacy = options.devtool.indexOf("@") >= 0;
- modern = options.devtool.indexOf("#") >= 0;
- comment = legacy && modern ? "\n//@ sourceURL=[url]\n//# sourceURL=[url]" :
- legacy ? "\n//@ sourceURL=[url]" :
- modern ? "\n//# sourceURL=[url]" :
- null;
- compiler.apply(new EvalDevToolModulePlugin(comment, options.output.devtoolModuleFilenameTemplate));
- }
-
- compiler.apply(new EntryOptionPlugin());
- compiler.applyPluginsBailResult("entry-option", options.context, options.entry);
-
- compiler.apply(
- new CompatibilityPlugin(),
- new HarmonyModulesPlugin(options.module),
- new AMDPlugin(options.module, options.amd || {}),
- new CommonJsPlugin(options.module),
- new LoaderPlugin(),
- new NodeStuffPlugin(options.node),
- new RequireJsStuffPlugin(),
- new APIPlugin(),
- new ConstPlugin(),
- new UseStrictPlugin(),
- new RequireIncludePlugin(),
- new RequireEnsurePlugin(),
- new RequireContextPlugin(options.resolve.modules, options.resolve.extensions, options.resolve.mainFiles),
- new ImportPlugin(options.module),
- new SystemPlugin(options.module)
- );
-
- compiler.apply(
- new EnsureChunkConditionsPlugin(),
- new RemoveParentModulesPlugin(),
- new RemoveEmptyChunksPlugin(),
- new MergeDuplicateChunksPlugin(),
- new FlagIncludedChunksPlugin(),
- new OccurrenceOrderPlugin(true),
- new FlagDependencyExportsPlugin(),
- new FlagDependencyUsagePlugin()
- );
-
- if(options.performance) {
- compiler.apply(new SizeLimitsPlugin(options.performance));
- }
-
- compiler.apply(new TemplatedPathPlugin());
-
- compiler.apply(new RecordIdsPlugin());
-
- compiler.apply(new WarnCaseSensitiveModulesPlugin());
-
- if(options.cache) {
- let CachePlugin = require("./CachePlugin");
- compiler.apply(new CachePlugin(typeof options.cache === "object" ? options.cache : null));
- }
-
- compiler.applyPlugins("after-plugins", compiler);
- if(!compiler.inputFileSystem) throw new Error("No input filesystem provided");
- compiler.resolvers.normal = ResolverFactory.createResolver(Object.assign({
- fileSystem: compiler.inputFileSystem
- }, options.resolve));
- compiler.resolvers.context = ResolverFactory.createResolver(Object.assign({
- fileSystem: compiler.inputFileSystem,
- resolveToContext: true
- }, options.resolve));
- compiler.resolvers.loader = ResolverFactory.createResolver(Object.assign({
- fileSystem: compiler.inputFileSystem
- }, options.resolveLoader));
- compiler.applyPlugins("after-resolvers", compiler);
- return options;
- }
-}
-
-module.exports = WebpackOptionsApply;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const OptionsApply = require("./OptionsApply"); + +const JavascriptModulesPlugin = require("./JavascriptModulesPlugin"); +const JsonModulesPlugin = require("./JsonModulesPlugin"); +const WebAssemblyModulesPlugin = require("./wasm/WebAssemblyModulesPlugin"); + +const LoaderTargetPlugin = require("./LoaderTargetPlugin"); +const FunctionModulePlugin = require("./FunctionModulePlugin"); +const EvalDevToolModulePlugin = require("./EvalDevToolModulePlugin"); +const SourceMapDevToolPlugin = require("./SourceMapDevToolPlugin"); +const EvalSourceMapDevToolPlugin = require("./EvalSourceMapDevToolPlugin"); + +const EntryOptionPlugin = require("./EntryOptionPlugin"); +const RecordIdsPlugin = require("./RecordIdsPlugin"); + +const APIPlugin = require("./APIPlugin"); +const ConstPlugin = require("./ConstPlugin"); +const RequireJsStuffPlugin = require("./RequireJsStuffPlugin"); +const NodeStuffPlugin = require("./NodeStuffPlugin"); +const CompatibilityPlugin = require("./CompatibilityPlugin"); + +const TemplatedPathPlugin = require("./TemplatedPathPlugin"); +const WarnCaseSensitiveModulesPlugin = require("./WarnCaseSensitiveModulesPlugin"); +const UseStrictPlugin = require("./UseStrictPlugin"); + +const LoaderPlugin = require("./dependencies/LoaderPlugin"); +const CommonJsPlugin = require("./dependencies/CommonJsPlugin"); +const HarmonyModulesPlugin = require("./dependencies/HarmonyModulesPlugin"); +const SystemPlugin = require("./dependencies/SystemPlugin"); +const ImportPlugin = require("./dependencies/ImportPlugin"); +const AMDPlugin = require("./dependencies/AMDPlugin"); +const RequireContextPlugin = require("./dependencies/RequireContextPlugin"); +const RequireEnsurePlugin = require("./dependencies/RequireEnsurePlugin"); +const RequireIncludePlugin = require("./dependencies/RequireIncludePlugin"); + +const WarnNoModeSetPlugin = require("./WarnNoModeSetPlugin"); + +const EnsureChunkConditionsPlugin = require("./optimize/EnsureChunkConditionsPlugin"); +const RemoveParentModulesPlugin = require("./optimize/RemoveParentModulesPlugin"); +const RemoveEmptyChunksPlugin = require("./optimize/RemoveEmptyChunksPlugin"); +const MergeDuplicateChunksPlugin = require("./optimize/MergeDuplicateChunksPlugin"); +const FlagIncludedChunksPlugin = require("./optimize/FlagIncludedChunksPlugin"); +const OccurrenceChunkOrderPlugin = require("./optimize/OccurrenceChunkOrderPlugin"); +const OccurrenceModuleOrderPlugin = require("./optimize/OccurrenceModuleOrderPlugin"); +const NaturalChunkOrderPlugin = require("./optimize/NaturalChunkOrderPlugin"); +const SideEffectsFlagPlugin = require("./optimize/SideEffectsFlagPlugin"); +const FlagDependencyUsagePlugin = require("./FlagDependencyUsagePlugin"); +const FlagDependencyExportsPlugin = require("./FlagDependencyExportsPlugin"); +const ModuleConcatenationPlugin = require("./optimize/ModuleConcatenationPlugin"); +const SplitChunksPlugin = require("./optimize/SplitChunksPlugin"); +const RuntimeChunkPlugin = require("./optimize/RuntimeChunkPlugin"); +const NoEmitOnErrorsPlugin = require("./NoEmitOnErrorsPlugin"); +const NamedModulesPlugin = require("./NamedModulesPlugin"); +const NamedChunksPlugin = require("./NamedChunksPlugin"); +const HashedModuleIdsPlugin = require("./HashedModuleIdsPlugin"); +const DefinePlugin = require("./DefinePlugin"); +const SizeLimitsPlugin = require("./performance/SizeLimitsPlugin"); +const WasmFinalizeExportsPlugin = require("./wasm/WasmFinalizeExportsPlugin"); + +class WebpackOptionsApply extends OptionsApply { + constructor() { + super(); + } + + process(options, compiler) { + let ExternalsPlugin; + compiler.outputPath = options.output.path; + compiler.recordsInputPath = options.recordsInputPath || options.recordsPath; + compiler.recordsOutputPath = + options.recordsOutputPath || options.recordsPath; + compiler.name = options.name; + compiler.dependencies = options.dependencies; + if (typeof options.target === "string") { + let JsonpTemplatePlugin; + let FetchCompileWasmTemplatePlugin; + let ReadFileCompileWasmTemplatePlugin; + let NodeSourcePlugin; + let NodeTargetPlugin; + let NodeTemplatePlugin; + + switch (options.target) { + case "web": + JsonpTemplatePlugin = require("./web/JsonpTemplatePlugin"); + FetchCompileWasmTemplatePlugin = require("./web/FetchCompileWasmTemplatePlugin"); + NodeSourcePlugin = require("./node/NodeSourcePlugin"); + new JsonpTemplatePlugin().apply(compiler); + new FetchCompileWasmTemplatePlugin({ + mangleImports: options.optimization.mangleWasmImports + }).apply(compiler); + new FunctionModulePlugin().apply(compiler); + new NodeSourcePlugin(options.node).apply(compiler); + new LoaderTargetPlugin(options.target).apply(compiler); + break; + case "webworker": { + let WebWorkerTemplatePlugin = require("./webworker/WebWorkerTemplatePlugin"); + FetchCompileWasmTemplatePlugin = require("./web/FetchCompileWasmTemplatePlugin"); + NodeSourcePlugin = require("./node/NodeSourcePlugin"); + new WebWorkerTemplatePlugin().apply(compiler); + new FetchCompileWasmTemplatePlugin({ + mangleImports: options.optimization.mangleWasmImports + }).apply(compiler); + new FunctionModulePlugin().apply(compiler); + new NodeSourcePlugin(options.node).apply(compiler); + new LoaderTargetPlugin(options.target).apply(compiler); + break; + } + case "node": + case "async-node": + NodeTemplatePlugin = require("./node/NodeTemplatePlugin"); + ReadFileCompileWasmTemplatePlugin = require("./node/ReadFileCompileWasmTemplatePlugin"); + NodeTargetPlugin = require("./node/NodeTargetPlugin"); + new NodeTemplatePlugin({ + asyncChunkLoading: options.target === "async-node" + }).apply(compiler); + new ReadFileCompileWasmTemplatePlugin({ + mangleImports: options.optimization.mangleWasmImports + }).apply(compiler); + new FunctionModulePlugin().apply(compiler); + new NodeTargetPlugin().apply(compiler); + new LoaderTargetPlugin("node").apply(compiler); + break; + case "node-webkit": + JsonpTemplatePlugin = require("./web/JsonpTemplatePlugin"); + NodeTargetPlugin = require("./node/NodeTargetPlugin"); + ExternalsPlugin = require("./ExternalsPlugin"); + new JsonpTemplatePlugin().apply(compiler); + new FunctionModulePlugin().apply(compiler); + new NodeTargetPlugin().apply(compiler); + new ExternalsPlugin("commonjs", "nw.gui").apply(compiler); + new LoaderTargetPlugin(options.target).apply(compiler); + break; + case "electron-main": + NodeTemplatePlugin = require("./node/NodeTemplatePlugin"); + NodeTargetPlugin = require("./node/NodeTargetPlugin"); + ExternalsPlugin = require("./ExternalsPlugin"); + new NodeTemplatePlugin({ + asyncChunkLoading: true + }).apply(compiler); + new FunctionModulePlugin().apply(compiler); + new NodeTargetPlugin().apply(compiler); + new ExternalsPlugin("commonjs", [ + "app", + "auto-updater", + "browser-window", + "clipboard", + "content-tracing", + "crash-reporter", + "dialog", + "electron", + "global-shortcut", + "ipc", + "ipc-main", + "menu", + "menu-item", + "native-image", + "original-fs", + "power-monitor", + "power-save-blocker", + "protocol", + "screen", + "session", + "shell", + "tray", + "web-contents" + ]).apply(compiler); + new LoaderTargetPlugin(options.target).apply(compiler); + break; + case "electron-renderer": + JsonpTemplatePlugin = require("./web/JsonpTemplatePlugin"); + FetchCompileWasmTemplatePlugin = require("./web/FetchCompileWasmTemplatePlugin"); + NodeTargetPlugin = require("./node/NodeTargetPlugin"); + ExternalsPlugin = require("./ExternalsPlugin"); + new JsonpTemplatePlugin().apply(compiler); + new FetchCompileWasmTemplatePlugin({ + mangleImports: options.optimization.mangleWasmImports + }).apply(compiler); + new FunctionModulePlugin().apply(compiler); + new NodeTargetPlugin().apply(compiler); + new ExternalsPlugin("commonjs", [ + "clipboard", + "crash-reporter", + "desktop-capturer", + "electron", + "ipc", + "ipc-renderer", + "native-image", + "original-fs", + "remote", + "screen", + "shell", + "web-frame" + ]).apply(compiler); + new LoaderTargetPlugin(options.target).apply(compiler); + break; + default: + throw new Error("Unsupported target '" + options.target + "'."); + } + } else if (options.target !== false) { + options.target(compiler); + } else { + throw new Error("Unsupported target '" + options.target + "'."); + } + + if (options.output.library || options.output.libraryTarget !== "var") { + const LibraryTemplatePlugin = require("./LibraryTemplatePlugin"); + new LibraryTemplatePlugin( + options.output.library, + options.output.libraryTarget, + options.output.umdNamedDefine, + options.output.auxiliaryComment || "", + options.output.libraryExport + ).apply(compiler); + } + if (options.externals) { + ExternalsPlugin = require("./ExternalsPlugin"); + new ExternalsPlugin( + options.output.libraryTarget, + options.externals + ).apply(compiler); + } + + let noSources; + let legacy; + let modern; + let comment; + if ( + options.devtool && + (options.devtool.includes("sourcemap") || + options.devtool.includes("source-map")) + ) { + const hidden = options.devtool.includes("hidden"); + const inline = options.devtool.includes("inline"); + const evalWrapped = options.devtool.includes("eval"); + const cheap = options.devtool.includes("cheap"); + const moduleMaps = options.devtool.includes("module"); + noSources = options.devtool.includes("nosources"); + legacy = options.devtool.includes("@"); + modern = options.devtool.includes("#"); + comment = + legacy && modern + ? "\n/*\n//@ source" + + "MappingURL=[url]\n//# source" + + "MappingURL=[url]\n*/" + : legacy + ? "\n/*\n//@ source" + "MappingURL=[url]\n*/" + : modern + ? "\n//# source" + "MappingURL=[url]" + : null; + const Plugin = evalWrapped + ? EvalSourceMapDevToolPlugin + : SourceMapDevToolPlugin; + new Plugin({ + filename: inline ? null : options.output.sourceMapFilename, + moduleFilenameTemplate: options.output.devtoolModuleFilenameTemplate, + fallbackModuleFilenameTemplate: + options.output.devtoolFallbackModuleFilenameTemplate, + append: hidden ? false : comment, + module: moduleMaps ? true : cheap ? false : true, + columns: cheap ? false : true, + lineToLine: options.output.devtoolLineToLine, + noSources: noSources, + namespace: options.output.devtoolNamespace + }).apply(compiler); + } else if (options.devtool && options.devtool.includes("eval")) { + legacy = options.devtool.includes("@"); + modern = options.devtool.includes("#"); + comment = + legacy && modern + ? "\n//@ sourceURL=[url]\n//# sourceURL=[url]" + : legacy + ? "\n//@ sourceURL=[url]" + : modern + ? "\n//# sourceURL=[url]" + : null; + new EvalDevToolModulePlugin({ + sourceUrlComment: comment, + moduleFilenameTemplate: options.output.devtoolModuleFilenameTemplate, + namespace: options.output.devtoolNamespace + }).apply(compiler); + } + + new JavascriptModulesPlugin().apply(compiler); + new JsonModulesPlugin().apply(compiler); + new WebAssemblyModulesPlugin({ + mangleImports: options.optimization.mangleWasmImports + }).apply(compiler); + + new EntryOptionPlugin().apply(compiler); + compiler.hooks.entryOption.call(options.context, options.entry); + + new CompatibilityPlugin().apply(compiler); + new HarmonyModulesPlugin(options.module).apply(compiler); + new AMDPlugin(options.module, options.amd || {}).apply(compiler); + new CommonJsPlugin(options.module).apply(compiler); + new LoaderPlugin().apply(compiler); + new NodeStuffPlugin(options.node).apply(compiler); + new RequireJsStuffPlugin().apply(compiler); + new APIPlugin().apply(compiler); + new ConstPlugin().apply(compiler); + new UseStrictPlugin().apply(compiler); + new RequireIncludePlugin().apply(compiler); + new RequireEnsurePlugin().apply(compiler); + new RequireContextPlugin( + options.resolve.modules, + options.resolve.extensions, + options.resolve.mainFiles + ).apply(compiler); + new ImportPlugin(options.module).apply(compiler); + new SystemPlugin(options.module).apply(compiler); + + if (typeof options.mode !== "string") { + new WarnNoModeSetPlugin().apply(compiler); + } + + new EnsureChunkConditionsPlugin().apply(compiler); + if (options.optimization.removeAvailableModules) { + new RemoveParentModulesPlugin().apply(compiler); + } + if (options.optimization.removeEmptyChunks) { + new RemoveEmptyChunksPlugin().apply(compiler); + } + if (options.optimization.mergeDuplicateChunks) { + new MergeDuplicateChunksPlugin().apply(compiler); + } + if (options.optimization.flagIncludedChunks) { + new FlagIncludedChunksPlugin().apply(compiler); + } + if (options.optimization.sideEffects) { + new SideEffectsFlagPlugin().apply(compiler); + } + if (options.optimization.providedExports) { + new FlagDependencyExportsPlugin().apply(compiler); + } + if (options.optimization.usedExports) { + new FlagDependencyUsagePlugin().apply(compiler); + } + if (options.optimization.concatenateModules) { + new ModuleConcatenationPlugin().apply(compiler); + } + if (options.optimization.splitChunks) { + new SplitChunksPlugin(options.optimization.splitChunks).apply(compiler); + } + if (options.optimization.runtimeChunk) { + new RuntimeChunkPlugin(options.optimization.runtimeChunk).apply(compiler); + } + if (options.optimization.noEmitOnErrors) { + new NoEmitOnErrorsPlugin().apply(compiler); + } + if (options.optimization.checkWasmTypes) { + new WasmFinalizeExportsPlugin().apply(compiler); + } + let moduleIds = options.optimization.moduleIds; + if (moduleIds === undefined) { + // TODO webpack 5 remove all these options + if (options.optimization.occurrenceOrder) { + moduleIds = "size"; + } + if (options.optimization.namedModules) { + moduleIds = "named"; + } + if (options.optimization.hashedModuleIds) { + moduleIds = "hashed"; + } + if (moduleIds === undefined) { + moduleIds = "natural"; + } + } + if (moduleIds) { + switch (moduleIds) { + case "natural": + // TODO webpack 5: see hint in Compilation.sortModules + break; + case "named": + new NamedModulesPlugin().apply(compiler); + break; + case "hashed": + new HashedModuleIdsPlugin().apply(compiler); + break; + case "size": + new OccurrenceModuleOrderPlugin({ + prioritiseInitial: true + }).apply(compiler); + break; + case "total-size": + new OccurrenceModuleOrderPlugin({ + prioritiseInitial: false + }).apply(compiler); + break; + default: + throw new Error( + `webpack bug: moduleIds: ${moduleIds} is not implemented` + ); + } + } + let chunkIds = options.optimization.chunkIds; + if (chunkIds === undefined) { + // TODO webpack 5 remove all these options + if (options.optimization.occurrenceOrder) { + // This looks weird but it's for backward-compat + // This bug already existed before adding this feature + chunkIds = "total-size"; + } + if (options.optimization.namedChunks) { + chunkIds = "named"; + } + if (chunkIds === undefined) { + chunkIds = "natural"; + } + } + if (chunkIds) { + switch (chunkIds) { + case "natural": + new NaturalChunkOrderPlugin().apply(compiler); + break; + case "named": + // TODO webapck 5: for backward-compat this need to have OccurrenceChunkOrderPlugin too + // The NamedChunksPlugin doesn't give every chunk a name + // This should be fixed, and the OccurrenceChunkOrderPlugin should be removed here. + new OccurrenceChunkOrderPlugin({ + prioritiseInitial: false + }).apply(compiler); + new NamedChunksPlugin().apply(compiler); + break; + case "size": + new OccurrenceChunkOrderPlugin({ + prioritiseInitial: true + }).apply(compiler); + break; + case "total-size": + new OccurrenceChunkOrderPlugin({ + prioritiseInitial: false + }).apply(compiler); + break; + default: + throw new Error( + `webpack bug: chunkIds: ${chunkIds} is not implemented` + ); + } + } + if (options.optimization.nodeEnv) { + new DefinePlugin({ + "process.env.NODE_ENV": JSON.stringify(options.optimization.nodeEnv) + }).apply(compiler); + } + if (options.optimization.minimize) { + for (const minimizer of options.optimization.minimizer) { + minimizer.apply(compiler); + } + } + + if (options.performance) { + new SizeLimitsPlugin(options.performance).apply(compiler); + } + + new TemplatedPathPlugin().apply(compiler); + + new RecordIdsPlugin({ + portableIds: options.optimization.portableRecords + }).apply(compiler); + + new WarnCaseSensitiveModulesPlugin().apply(compiler); + + if (options.cache) { + const CachePlugin = require("./CachePlugin"); + new CachePlugin( + typeof options.cache === "object" ? options.cache : null + ).apply(compiler); + } + + compiler.hooks.afterPlugins.call(compiler); + if (!compiler.inputFileSystem) { + throw new Error("No input filesystem provided"); + } + compiler.resolverFactory.hooks.resolveOptions + .for("normal") + .tap("WebpackOptionsApply", resolveOptions => { + return Object.assign( + { + fileSystem: compiler.inputFileSystem + }, + options.resolve, + resolveOptions + ); + }); + compiler.resolverFactory.hooks.resolveOptions + .for("context") + .tap("WebpackOptionsApply", resolveOptions => { + return Object.assign( + { + fileSystem: compiler.inputFileSystem, + resolveToContext: true + }, + options.resolve, + resolveOptions + ); + }); + compiler.resolverFactory.hooks.resolveOptions + .for("loader") + .tap("WebpackOptionsApply", resolveOptions => { + return Object.assign( + { + fileSystem: compiler.inputFileSystem + }, + options.resolveLoader, + resolveOptions + ); + }); + compiler.hooks.afterResolvers.call(compiler); + return options; + } +} + +module.exports = WebpackOptionsApply; diff --git a/node_modules/webpack/lib/WebpackOptionsDefaulter.js b/node_modules/webpack/lib/WebpackOptionsDefaulter.js index 385578f50..def82855a 100644 --- a/node_modules/webpack/lib/WebpackOptionsDefaulter.js +++ b/node_modules/webpack/lib/WebpackOptionsDefaulter.js @@ -1,129 +1,372 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const OptionsDefaulter = require("./OptionsDefaulter");
-const Template = require("./Template");
-
-class WebpackOptionsDefaulter extends OptionsDefaulter {
- constructor() {
- super();
- this.set("devtool", false);
- this.set("cache", true);
-
- this.set("context", process.cwd());
- this.set("target", "web");
-
- this.set("module", "call", value => Object.assign({}, value));
- this.set("module.unknownContextRequest", ".");
- this.set("module.unknownContextRegExp", false);
- this.set("module.unknownContextRecursive", true);
- this.set("module.unknownContextCritical", true);
- this.set("module.exprContextRequest", ".");
- this.set("module.exprContextRegExp", false);
- this.set("module.exprContextRecursive", true);
- this.set("module.exprContextCritical", true);
- this.set("module.wrappedContextRegExp", /.*/);
- this.set("module.wrappedContextRecursive", true);
- this.set("module.wrappedContextCritical", false);
- this.set("module.strictExportPresence", false);
- this.set("module.strictThisContextOnImports", false);
- this.set("module.unsafeCache", true);
-
- this.set("output", "call", (value, options) => {
- if(typeof value === "string") {
- return {
- filename: value
- };
- } else if(typeof value !== "object") {
- return {};
- } else {
- return Object.assign({}, value);
- }
- });
- this.set("output.filename", "[name].js");
- this.set("output.chunkFilename", "make", (options) => {
- const filename = options.output.filename;
- return filename.indexOf("[name]") >= 0 ? filename.replace("[name]", "[id]") : "[id]." + filename;
- });
- this.set("output.library", "");
- this.set("output.hotUpdateFunction", "make", (options) => {
- return Template.toIdentifier("webpackHotUpdate" + options.output.library);
- });
- this.set("output.jsonpFunction", "make", (options) => {
- return Template.toIdentifier("webpackJsonp" + options.output.library);
- });
- this.set("output.libraryTarget", "var");
- this.set("output.path", process.cwd());
- this.set("output.sourceMapFilename", "[file].map[query]");
- this.set("output.hotUpdateChunkFilename", "[id].[hash].hot-update.js");
- this.set("output.hotUpdateMainFilename", "[hash].hot-update.json");
- this.set("output.crossOriginLoading", false);
- this.set("output.chunkLoadTimeout", 120000);
- this.set("output.hashFunction", "md5");
- this.set("output.hashDigest", "hex");
- this.set("output.hashDigestLength", 20);
- this.set("output.devtoolLineToLine", false);
- this.set("output.strictModuleExceptionHandling", false);
-
- this.set("node", "call", value => {
- if(typeof value === "boolean") {
- return value;
- } else {
- return Object.assign({}, value);
- }
- });
- this.set("node.console", false);
- this.set("node.process", true);
- this.set("node.global", true);
- this.set("node.Buffer", true);
- this.set("node.setImmediate", true);
- this.set("node.__filename", "mock");
- this.set("node.__dirname", "mock");
-
- this.set("performance", "call", value => {
- if(typeof value === "boolean") {
- return value;
- } else {
- return Object.assign({}, value);
- }
- });
- this.set("performance.maxAssetSize", 250000);
- this.set("performance.maxEntrypointSize", 250000);
- this.set("performance.hints", false);
-
- this.set("resolve", "call", value => Object.assign({}, value));
- this.set("resolve.unsafeCache", true);
- this.set("resolve.modules", ["node_modules"]);
- this.set("resolve.extensions", [".js", ".json"]);
- this.set("resolve.mainFiles", ["index"]);
- this.set("resolve.aliasFields", "make", (options) => {
- if(options.target === "web" || options.target === "webworker")
- return ["browser"];
- else
- return [];
- });
- this.set("resolve.mainFields", "make", (options) => {
- if(options.target === "web" || options.target === "webworker")
- return ["browser", "module", "main"];
- else
- return ["module", "main"];
- });
- this.set("resolve.cacheWithContext", "make", (options) => {
- return Array.isArray(options.resolve.plugins) && options.resolve.plugins.length > 0;
- });
-
- this.set("resolveLoader", "call", value => Object.assign({}, value));
- this.set("resolveLoader.unsafeCache", true);
- this.set("resolveLoader.mainFields", ["loader", "main"]);
- this.set("resolveLoader.extensions", [".js", ".json"]);
- this.set("resolveLoader.mainFiles", ["index"]);
- this.set("resolveLoader.cacheWithContext", "make", (options) => {
- return Array.isArray(options.resolveLoader.plugins) && options.resolveLoader.plugins.length > 0;
- });
- }
-}
-
-module.exports = WebpackOptionsDefaulter;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const path = require("path"); + +const OptionsDefaulter = require("./OptionsDefaulter"); +const Template = require("./Template"); + +const isProductionLikeMode = options => { + return options.mode === "production" || !options.mode; +}; + +const isWebLikeTarget = options => { + return options.target === "web" || options.target === "webworker"; +}; + +const getDevtoolNamespace = library => { + // if options.output.library is a string + if (Array.isArray(library)) { + return library.join("."); + } else if (typeof library === "object") { + return getDevtoolNamespace(library.root); + } + return library || ""; +}; + +class WebpackOptionsDefaulter extends OptionsDefaulter { + constructor() { + super(); + + this.set("entry", "./src"); + + this.set( + "devtool", + "make", + options => (options.mode === "development" ? "eval" : false) + ); + this.set("cache", "make", options => options.mode === "development"); + + this.set("context", process.cwd()); + this.set("target", "web"); + + this.set("module", "call", value => Object.assign({}, value)); + this.set("module.unknownContextRequest", "."); + this.set("module.unknownContextRegExp", false); + this.set("module.unknownContextRecursive", true); + this.set("module.unknownContextCritical", true); + this.set("module.exprContextRequest", "."); + this.set("module.exprContextRegExp", false); + this.set("module.exprContextRecursive", true); + this.set("module.exprContextCritical", true); + this.set("module.wrappedContextRegExp", /.*/); + this.set("module.wrappedContextRecursive", true); + this.set("module.wrappedContextCritical", false); + this.set("module.strictExportPresence", false); + this.set("module.strictThisContextOnImports", false); + this.set("module.unsafeCache", "make", options => !!options.cache); + this.set("module.rules", []); + this.set("module.defaultRules", "make", options => [ + { + type: "javascript/auto", + resolve: {} + }, + { + test: /\.mjs$/i, + type: "javascript/esm", + resolve: { + mainFields: + options.target === "web" || + options.target === "webworker" || + options.target === "electron-renderer" + ? ["browser", "main"] + : ["main"] + } + }, + { + test: /\.json$/i, + type: "json" + }, + { + test: /\.wasm$/i, + type: "webassembly/experimental" + } + ]); + + this.set("output", "call", (value, options) => { + if (typeof value === "string") { + return { + filename: value + }; + } else if (typeof value !== "object") { + return {}; + } else { + return Object.assign({}, value); + } + }); + + this.set("output.filename", "[name].js"); + this.set("output.chunkFilename", "make", options => { + const filename = options.output.filename; + if (typeof filename !== "function") { + const hasName = filename.includes("[name]"); + const hasId = filename.includes("[id]"); + const hasChunkHash = filename.includes("[chunkhash]"); + // Anything changing depending on chunk is fine + if (hasChunkHash || hasName || hasId) return filename; + // Elsewise prefix "[id]." in front of the basename to make it changing + return filename.replace(/(^|\/)([^/]*(?:\?|$))/, "$1[id].$2"); + } + return "[id].js"; + }); + this.set("output.webassemblyModuleFilename", "[modulehash].module.wasm"); + this.set("output.library", ""); + this.set("output.hotUpdateFunction", "make", options => { + return Template.toIdentifier( + "webpackHotUpdate" + Template.toIdentifier(options.output.library) + ); + }); + this.set("output.jsonpFunction", "make", options => { + return Template.toIdentifier( + "webpackJsonp" + Template.toIdentifier(options.output.library) + ); + }); + this.set("output.chunkCallbackName", "make", options => { + return Template.toIdentifier( + "webpackChunk" + Template.toIdentifier(options.output.library) + ); + }); + this.set("output.globalObject", "make", options => { + switch (options.target) { + case "web": + case "electron-renderer": + case "node-webkit": + return "window"; + case "webworker": + return "self"; + case "node": + case "async-node": + case "electron-main": + return "global"; + default: + return "self"; + } + }); + this.set("output.devtoolNamespace", "make", options => { + return getDevtoolNamespace(options.output.library); + }); + this.set("output.libraryTarget", "var"); + this.set("output.path", path.join(process.cwd(), "dist")); + this.set( + "output.pathinfo", + "make", + options => options.mode === "development" + ); + this.set("output.sourceMapFilename", "[file].map[query]"); + this.set("output.hotUpdateChunkFilename", "[id].[hash].hot-update.js"); + this.set("output.hotUpdateMainFilename", "[hash].hot-update.json"); + this.set("output.crossOriginLoading", false); + this.set("output.jsonpScriptType", false); + this.set("output.chunkLoadTimeout", 120000); + this.set("output.hashFunction", "md4"); + this.set("output.hashDigest", "hex"); + this.set("output.hashDigestLength", 20); + this.set("output.devtoolLineToLine", false); + this.set("output.strictModuleExceptionHandling", false); + + this.set("node", "call", value => { + if (typeof value === "boolean") { + return value; + } else { + return Object.assign({}, value); + } + }); + this.set("node.console", false); + this.set("node.process", true); + this.set("node.global", true); + this.set("node.Buffer", true); + this.set("node.setImmediate", true); + this.set("node.__filename", "mock"); + this.set("node.__dirname", "mock"); + + this.set("performance", "call", (value, options) => { + if (value === false) return false; + if ( + value === undefined && + (!isProductionLikeMode(options) || !isWebLikeTarget(options)) + ) + return false; + return Object.assign({}, value); + }); + this.set("performance.maxAssetSize", 250000); + this.set("performance.maxEntrypointSize", 250000); + this.set( + "performance.hints", + "make", + options => (isProductionLikeMode(options) ? "warning" : false) + ); + + this.set("optimization", "call", value => Object.assign({}, value)); + this.set("optimization.removeAvailableModules", true); + this.set("optimization.removeEmptyChunks", true); + this.set("optimization.mergeDuplicateChunks", true); + this.set("optimization.flagIncludedChunks", "make", options => + isProductionLikeMode(options) + ); + // TODO webpack 5 add `moduleIds: "named"` default for development + // TODO webpack 5 add `moduleIds: "size"` default for production + // TODO webpack 5 remove optimization.occurrenceOrder + this.set("optimization.occurrenceOrder", "make", options => + isProductionLikeMode(options) + ); + this.set("optimization.sideEffects", "make", options => + isProductionLikeMode(options) + ); + this.set("optimization.providedExports", true); + this.set("optimization.usedExports", "make", options => + isProductionLikeMode(options) + ); + this.set("optimization.concatenateModules", "make", options => + isProductionLikeMode(options) + ); + this.set("optimization.splitChunks", {}); + this.set("optimization.splitChunks.hidePathInfo", "make", options => { + return isProductionLikeMode(options); + }); + this.set("optimization.splitChunks.chunks", "async"); + this.set("optimization.splitChunks.minSize", "make", options => { + return isProductionLikeMode(options) ? 30000 : 10000; + }); + this.set("optimization.splitChunks.minChunks", 1); + this.set("optimization.splitChunks.maxAsyncRequests", "make", options => { + return isProductionLikeMode(options) ? 5 : Infinity; + }); + this.set("optimization.splitChunks.automaticNameDelimiter", "~"); + this.set("optimization.splitChunks.maxInitialRequests", "make", options => { + return isProductionLikeMode(options) ? 3 : Infinity; + }); + this.set("optimization.splitChunks.name", true); + this.set("optimization.splitChunks.cacheGroups", {}); + this.set("optimization.splitChunks.cacheGroups.default", { + automaticNamePrefix: "", + reuseExistingChunk: true, + minChunks: 2, + priority: -20 + }); + this.set("optimization.splitChunks.cacheGroups.vendors", { + automaticNamePrefix: "vendors", + test: /[\\/]node_modules[\\/]/, + priority: -10 + }); + this.set("optimization.runtimeChunk", "call", value => { + if (value === "single") { + return { + name: "runtime" + }; + } + if (value === true || value === "multiple") { + return { + name: entrypoint => `runtime~${entrypoint.name}` + }; + } + return value; + }); + this.set("optimization.noEmitOnErrors", "make", options => + isProductionLikeMode(options) + ); + this.set("optimization.checkWasmTypes", "make", options => + isProductionLikeMode(options) + ); + this.set("optimization.mangleWasmImports", false); + // TODO webpack 5 remove optimization.namedModules + this.set( + "optimization.namedModules", + "make", + options => options.mode === "development" + ); + this.set("optimization.hashedModuleIds", false); + // TODO webpack 5 add `chunkIds: "named"` default for development + // TODO webpack 5 add `chunkIds: "size"` default for production + // TODO webpack 5 remove optimization.namedChunks + this.set( + "optimization.namedChunks", + "make", + options => options.mode === "development" + ); + this.set( + "optimization.portableRecords", + "make", + options => + !!( + options.recordsInputPath || + options.recordsOutputPath || + options.recordsPath + ) + ); + this.set("optimization.minimize", "make", options => + isProductionLikeMode(options) + ); + this.set("optimization.minimizer", "make", options => [ + { + apply: compiler => { + // Lazy load the uglifyjs plugin + const UglifyJsPlugin = require("uglifyjs-webpack-plugin"); + const SourceMapDevToolPlugin = require("./SourceMapDevToolPlugin"); + new UglifyJsPlugin({ + cache: true, + parallel: true, + sourceMap: + (options.devtool && /source-?map/.test(options.devtool)) || + (options.plugins && + options.plugins.some(p => p instanceof SourceMapDevToolPlugin)) + }).apply(compiler); + } + } + ]); + this.set("optimization.nodeEnv", "make", options => { + // TODO: In webpack 5, it should return `false` when mode is `none` + return options.mode || "production"; + }); + + this.set("resolve", "call", value => Object.assign({}, value)); + this.set("resolve.unsafeCache", true); + this.set("resolve.modules", ["node_modules"]); + this.set("resolve.extensions", [".wasm", ".mjs", ".js", ".json"]); + this.set("resolve.mainFiles", ["index"]); + this.set("resolve.aliasFields", "make", options => { + if ( + options.target === "web" || + options.target === "webworker" || + options.target === "electron-renderer" + ) { + return ["browser"]; + } else { + return []; + } + }); + this.set("resolve.mainFields", "make", options => { + if ( + options.target === "web" || + options.target === "webworker" || + options.target === "electron-renderer" + ) { + return ["browser", "module", "main"]; + } else { + return ["module", "main"]; + } + }); + this.set("resolve.cacheWithContext", "make", options => { + return ( + Array.isArray(options.resolve.plugins) && + options.resolve.plugins.length > 0 + ); + }); + + this.set("resolveLoader", "call", value => Object.assign({}, value)); + this.set("resolveLoader.unsafeCache", true); + this.set("resolveLoader.mainFields", ["loader", "main"]); + this.set("resolveLoader.extensions", [".js", ".json"]); + this.set("resolveLoader.mainFiles", ["index"]); + this.set("resolveLoader.cacheWithContext", "make", options => { + return ( + Array.isArray(options.resolveLoader.plugins) && + options.resolveLoader.plugins.length > 0 + ); + }); + } +} + +module.exports = WebpackOptionsDefaulter; diff --git a/node_modules/webpack/lib/WebpackOptionsValidationError.js b/node_modules/webpack/lib/WebpackOptionsValidationError.js index 4fa72d19b..d66cb2ccc 100644 --- a/node_modules/webpack/lib/WebpackOptionsValidationError.js +++ b/node_modules/webpack/lib/WebpackOptionsValidationError.js @@ -1,219 +1,344 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Gajus Kuizinas @gajus
-*/
-"use strict";
-
-const WebpackError = require("./WebpackError");
-const webpackOptionsSchema = require("../schemas/webpackOptionsSchema.json");
-
-const getSchemaPart = (path, parents, additionalPath) => {
- parents = parents || 0;
- path = path.split("/");
- path = path.slice(0, path.length - parents);
- if(additionalPath) {
- additionalPath = additionalPath.split("/");
- path = path.concat(additionalPath);
- }
- let schemaPart = webpackOptionsSchema;
- for(let i = 1; i < path.length; i++) {
- const inner = schemaPart[path[i]];
- if(inner)
- schemaPart = inner;
- }
- return schemaPart;
-};
-
-const getSchemaPartText = (schemaPart, additionalPath) => {
- if(additionalPath) {
- for(let i = 0; i < additionalPath.length; i++) {
- const inner = schemaPart[additionalPath[i]];
- if(inner)
- schemaPart = inner;
- }
- }
- while(schemaPart.$ref) schemaPart = getSchemaPart(schemaPart.$ref);
- let schemaText = WebpackOptionsValidationError.formatSchema(schemaPart);
- if(schemaPart.description)
- schemaText += `\n-> ${schemaPart.description}`;
- return schemaText;
-};
-
-const getSchemaPartDescription = schemaPart => {
- while(schemaPart.$ref) schemaPart = getSchemaPart(schemaPart.$ref);
- if(schemaPart.description)
- return `\n-> ${schemaPart.description}`;
- return "";
-};
-
-const filterChildren = children => {
- return children.filter(err => err.keyword !== "anyOf" && err.keyword !== "allOf" && err.keyword !== "oneOf");
-};
-
-const indent = (str, prefix, firstLine) => {
- if(firstLine) {
- return prefix + str.replace(/\n(?!$)/g, "\n" + prefix);
- } else {
- return str.replace(/\n(?!$)/g, `\n${prefix}`);
- }
-};
-
-class WebpackOptionsValidationError extends WebpackError {
- constructor(validationErrors) {
- super();
-
- this.name = "WebpackOptionsValidationError";
- this.message = "Invalid configuration object. " +
- "Webpack has been initialised using a configuration object that does not match the API schema.\n" +
- validationErrors.map(err => " - " + indent(WebpackOptionsValidationError.formatValidationError(err), " ", false)).join("\n");
- this.validationErrors = validationErrors;
-
- Error.captureStackTrace(this, this.constructor);
- }
-
- static formatSchema(schema, prevSchemas) {
- prevSchemas = prevSchemas || [];
-
- const formatInnerSchema = (innerSchema, addSelf) => {
- if(!addSelf) return WebpackOptionsValidationError.formatSchema(innerSchema, prevSchemas);
- if(prevSchemas.indexOf(innerSchema) >= 0) return "(recursive)";
- return WebpackOptionsValidationError.formatSchema(innerSchema, prevSchemas.concat(schema));
- };
-
- if(schema.type === "string") {
- if(schema.minLength === 1)
- return "non-empty string";
- else if(schema.minLength > 1)
- return `string (min length ${schema.minLength})`;
- return "string";
- } else if(schema.type === "boolean") {
- return "boolean";
- } else if(schema.type === "number") {
- return "number";
- } else if(schema.type === "object") {
- if(schema.properties) {
- const required = schema.required || [];
- return `object { ${Object.keys(schema.properties).map(property => {
- if(required.indexOf(property) < 0) return property + "?";
- return property;
- }).concat(schema.additionalProperties ? ["..."] : []).join(", ")} }`;
- }
- if(schema.additionalProperties) {
- return `object { <key>: ${formatInnerSchema(schema.additionalProperties)} }`;
- }
- return "object";
- } else if(schema.type === "array") {
- return `[${formatInnerSchema(schema.items)}]`;
- }
-
- switch(schema.instanceof) {
- case "Function":
- return "function";
- case "RegExp":
- return "RegExp";
- }
- if(schema.$ref) return formatInnerSchema(getSchemaPart(schema.$ref), true);
- if(schema.allOf) return schema.allOf.map(formatInnerSchema).join(" & ");
- if(schema.oneOf) return schema.oneOf.map(formatInnerSchema).join(" | ");
- if(schema.anyOf) return schema.anyOf.map(formatInnerSchema).join(" | ");
- if(schema.enum) return schema.enum.map(item => JSON.stringify(item)).join(" | ");
- return JSON.stringify(schema, 0, 2);
- }
-
- static formatValidationError(err) {
- const dataPath = `configuration${err.dataPath}`;
- if(err.keyword === "additionalProperties") {
- const baseMessage = `${dataPath} has an unknown property '${err.params.additionalProperty}'. These properties are valid:\n${getSchemaPartText(err.parentSchema)}`;
- if(!err.dataPath) {
- switch(err.params.additionalProperty) {
- case "debug":
- return `${baseMessage}\n` +
- "The 'debug' property was removed in webpack 2.\n" +
- "Loaders should be updated to allow passing this option via loader options in module.rules.\n" +
- "Until loaders are updated one can use the LoaderOptionsPlugin to switch loaders into debug mode:\n" +
- "plugins: [\n" +
- " new webpack.LoaderOptionsPlugin({\n" +
- " debug: true\n" +
- " })\n" +
- "]";
- }
- return baseMessage + "\n" +
- "For typos: please correct them.\n" +
- "For loader options: webpack 2 no longer allows custom properties in configuration.\n" +
- " Loaders should be updated to allow passing options via loader options in module.rules.\n" +
- " Until loaders are updated one can use the LoaderOptionsPlugin to pass these options to the loader:\n" +
- " plugins: [\n" +
- " new webpack.LoaderOptionsPlugin({\n" +
- " // test: /\\.xxx$/, // may apply this only for some modules\n" +
- " options: {\n" +
- ` ${err.params.additionalProperty}: ...\n` +
- " }\n" +
- " })\n" +
- " ]";
- }
- return baseMessage;
- } else if(err.keyword === "oneOf" || err.keyword === "anyOf") {
- if(err.children && err.children.length > 0) {
- if(err.schema.length === 1) {
- const lastChild = err.children[err.children.length - 1];
- const remainingChildren = err.children.slice(0, err.children.length - 1);
- return WebpackOptionsValidationError.formatValidationError(Object.assign({}, lastChild, {
- children: remainingChildren,
- parentSchema: Object.assign({}, err.parentSchema, lastChild.parentSchema)
- }));
- }
- return `${dataPath} should be one of these:\n${getSchemaPartText(err.parentSchema)}\n` +
- `Details:\n${filterChildren(err.children).map(err => " * " + indent(WebpackOptionsValidationError.formatValidationError(err), " ", false)).join("\n")}`;
- }
- return `${dataPath} should be one of these:\n${getSchemaPartText(err.parentSchema)}`;
-
- } else if(err.keyword === "enum") {
- if(err.parentSchema && err.parentSchema.enum && err.parentSchema.enum.length === 1) {
- return `${dataPath} should be ${getSchemaPartText(err.parentSchema)}`;
- }
- return `${dataPath} should be one of these:\n${getSchemaPartText(err.parentSchema)}`;
- } else if(err.keyword === "allOf") {
- return `${dataPath} should be:\n${getSchemaPartText(err.parentSchema)}`;
- } else if(err.keyword === "type") {
- switch(err.params.type) {
- case "object":
- return `${dataPath} should be an object.${getSchemaPartDescription(err.parentSchema)}`;
- case "string":
- return `${dataPath} should be a string.${getSchemaPartDescription(err.parentSchema)}`;
- case "boolean":
- return `${dataPath} should be a boolean.${getSchemaPartDescription(err.parentSchema)}`;
- case "number":
- return `${dataPath} should be a number.${getSchemaPartDescription(err.parentSchema)}`;
- case "array":
- return `${dataPath} should be an array:\n${getSchemaPartText(err.parentSchema)}`;
- }
- return `${dataPath} should be ${err.params.type}:\n${getSchemaPartText(err.parentSchema)}`;
- } else if(err.keyword === "instanceof") {
- return `${dataPath} should be an instance of ${getSchemaPartText(err.parentSchema)}`;
- } else if(err.keyword === "required") {
- const missingProperty = err.params.missingProperty.replace(/^\./, "");
- return `${dataPath} misses the property '${missingProperty}'.\n${getSchemaPartText(err.parentSchema, ["properties", missingProperty])}`;
- } else if(err.keyword === "minimum") {
- return `${dataPath} ${err.message}.${getSchemaPartDescription(err.parentSchema)}`;
- } else if(err.keyword === "uniqueItems") {
- return `${dataPath} should not contain the item '${err.data[err.params.i]}' twice.${getSchemaPartDescription(err.parentSchema)}`;
- } else if(err.keyword === "minLength" || err.keyword === "minItems" || err.keyword === "minProperties") {
- if(err.params.limit === 1)
- return `${dataPath} should not be empty.${getSchemaPartDescription(err.parentSchema)}`;
- else
- return `${dataPath} ${err.message}${getSchemaPartDescription(err.parentSchema)}`;
- } else if(err.keyword === "absolutePath") {
- const baseMessage = `${dataPath}: ${err.message}${getSchemaPartDescription(err.parentSchema)}`;
- if(dataPath === "configuration.output.filename") {
- return `${baseMessage}\n` +
- "Please use output.path to specify absolute path and output.filename for the file name.";
- }
- return baseMessage;
- } else {
- // eslint-disable-line no-fallthrough
- return `${dataPath} ${err.message} (${JSON.stringify(err, 0, 2)}).\n${getSchemaPartText(err.parentSchema)}`;
- }
- }
-}
-
-module.exports = WebpackOptionsValidationError;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Gajus Kuizinas @gajus +*/ +"use strict"; + +const WebpackError = require("./WebpackError"); +const webpackOptionsSchema = require("../schemas/WebpackOptions.json"); + +const getSchemaPart = (path, parents, additionalPath) => { + parents = parents || 0; + path = path.split("/"); + path = path.slice(0, path.length - parents); + if (additionalPath) { + additionalPath = additionalPath.split("/"); + path = path.concat(additionalPath); + } + let schemaPart = webpackOptionsSchema; + for (let i = 1; i < path.length; i++) { + const inner = schemaPart[path[i]]; + if (inner) schemaPart = inner; + } + return schemaPart; +}; + +const getSchemaPartText = (schemaPart, additionalPath) => { + if (additionalPath) { + for (let i = 0; i < additionalPath.length; i++) { + const inner = schemaPart[additionalPath[i]]; + if (inner) schemaPart = inner; + } + } + while (schemaPart.$ref) { + schemaPart = getSchemaPart(schemaPart.$ref); + } + let schemaText = WebpackOptionsValidationError.formatSchema(schemaPart); + if (schemaPart.description) { + schemaText += `\n-> ${schemaPart.description}`; + } + return schemaText; +}; + +const getSchemaPartDescription = schemaPart => { + while (schemaPart.$ref) { + schemaPart = getSchemaPart(schemaPart.$ref); + } + if (schemaPart.description) { + return `\n-> ${schemaPart.description}`; + } + return ""; +}; + +const filterChildren = children => { + return children.filter( + err => + err.keyword !== "anyOf" && + err.keyword !== "allOf" && + err.keyword !== "oneOf" + ); +}; + +const indent = (str, prefix, firstLine) => { + if (firstLine) { + return prefix + str.replace(/\n(?!$)/g, "\n" + prefix); + } else { + return str.replace(/\n(?!$)/g, `\n${prefix}`); + } +}; + +class WebpackOptionsValidationError extends WebpackError { + constructor(validationErrors) { + super( + "Invalid configuration object. " + + "Webpack has been initialised using a configuration object that does not match the API schema.\n" + + validationErrors + .map( + err => + " - " + + indent( + WebpackOptionsValidationError.formatValidationError(err), + " ", + false + ) + ) + .join("\n") + ); + + this.name = "WebpackOptionsValidationError"; + this.validationErrors = validationErrors; + + Error.captureStackTrace(this, this.constructor); + } + + static formatSchema(schema, prevSchemas) { + prevSchemas = prevSchemas || []; + + const formatInnerSchema = (innerSchema, addSelf) => { + if (!addSelf) { + return WebpackOptionsValidationError.formatSchema( + innerSchema, + prevSchemas + ); + } + if (prevSchemas.includes(innerSchema)) { + return "(recursive)"; + } + return WebpackOptionsValidationError.formatSchema( + innerSchema, + prevSchemas.concat(schema) + ); + }; + + if (schema.type === "string") { + if (schema.minLength === 1) { + return "non-empty string"; + } + if (schema.minLength > 1) { + return `string (min length ${schema.minLength})`; + } + return "string"; + } + if (schema.type === "boolean") { + return "boolean"; + } + if (schema.type === "number") { + return "number"; + } + if (schema.type === "object") { + if (schema.properties) { + const required = schema.required || []; + return `object { ${Object.keys(schema.properties) + .map(property => { + if (!required.includes(property)) return property + "?"; + return property; + }) + .concat(schema.additionalProperties ? ["…"] : []) + .join(", ")} }`; + } + if (schema.additionalProperties) { + return `object { <key>: ${formatInnerSchema( + schema.additionalProperties + )} }`; + } + return "object"; + } + if (schema.type === "array") { + return `[${formatInnerSchema(schema.items)}]`; + } + + switch (schema.instanceof) { + case "Function": + return "function"; + case "RegExp": + return "RegExp"; + } + + if (schema.$ref) { + return formatInnerSchema(getSchemaPart(schema.$ref), true); + } + if (schema.allOf) { + return schema.allOf.map(formatInnerSchema).join(" & "); + } + if (schema.oneOf) { + return schema.oneOf.map(formatInnerSchema).join(" | "); + } + if (schema.anyOf) { + return schema.anyOf.map(formatInnerSchema).join(" | "); + } + if (schema.enum) { + return schema.enum.map(item => JSON.stringify(item)).join(" | "); + } + return JSON.stringify(schema, null, 2); + } + + static formatValidationError(err) { + const dataPath = `configuration${err.dataPath}`; + if (err.keyword === "additionalProperties") { + const baseMessage = `${dataPath} has an unknown property '${ + err.params.additionalProperty + }'. These properties are valid:\n${getSchemaPartText(err.parentSchema)}`; + if (!err.dataPath) { + switch (err.params.additionalProperty) { + case "debug": + return ( + `${baseMessage}\n` + + "The 'debug' property was removed in webpack 2.0.0.\n" + + "Loaders should be updated to allow passing this option via loader options in module.rules.\n" + + "Until loaders are updated one can use the LoaderOptionsPlugin to switch loaders into debug mode:\n" + + "plugins: [\n" + + " new webpack.LoaderOptionsPlugin({\n" + + " debug: true\n" + + " })\n" + + "]" + ); + } + return ( + `${baseMessage}\n` + + "For typos: please correct them.\n" + + "For loader options: webpack >= v2.0.0 no longer allows custom properties in configuration.\n" + + " Loaders should be updated to allow passing options via loader options in module.rules.\n" + + " Until loaders are updated one can use the LoaderOptionsPlugin to pass these options to the loader:\n" + + " plugins: [\n" + + " new webpack.LoaderOptionsPlugin({\n" + + " // test: /\\.xxx$/, // may apply this only for some modules\n" + + " options: {\n" + + ` ${err.params.additionalProperty}: …\n` + + " }\n" + + " })\n" + + " ]" + ); + } + return baseMessage; + } else if (err.keyword === "oneOf" || err.keyword === "anyOf") { + if (err.children && err.children.length > 0) { + if (err.schema.length === 1) { + const lastChild = err.children[err.children.length - 1]; + const remainingChildren = err.children.slice( + 0, + err.children.length - 1 + ); + return WebpackOptionsValidationError.formatValidationError( + Object.assign({}, lastChild, { + children: remainingChildren, + parentSchema: Object.assign( + {}, + err.parentSchema, + lastChild.parentSchema + ) + }) + ); + } + return ( + `${dataPath} should be one of these:\n${getSchemaPartText( + err.parentSchema + )}\n` + + `Details:\n${filterChildren(err.children) + .map( + err => + " * " + + indent( + WebpackOptionsValidationError.formatValidationError(err), + " ", + false + ) + ) + .join("\n")}` + ); + } + return `${dataPath} should be one of these:\n${getSchemaPartText( + err.parentSchema + )}`; + } else if (err.keyword === "enum") { + if ( + err.parentSchema && + err.parentSchema.enum && + err.parentSchema.enum.length === 1 + ) { + return `${dataPath} should be ${getSchemaPartText(err.parentSchema)}`; + } + return `${dataPath} should be one of these:\n${getSchemaPartText( + err.parentSchema + )}`; + } else if (err.keyword === "allOf") { + return `${dataPath} should be:\n${getSchemaPartText(err.parentSchema)}`; + } else if (err.keyword === "type") { + switch (err.params.type) { + case "object": + return `${dataPath} should be an object.${getSchemaPartDescription( + err.parentSchema + )}`; + case "string": + return `${dataPath} should be a string.${getSchemaPartDescription( + err.parentSchema + )}`; + case "boolean": + return `${dataPath} should be a boolean.${getSchemaPartDescription( + err.parentSchema + )}`; + case "number": + return `${dataPath} should be a number.${getSchemaPartDescription( + err.parentSchema + )}`; + case "array": + return `${dataPath} should be an array:\n${getSchemaPartText( + err.parentSchema + )}`; + } + return `${dataPath} should be ${err.params.type}:\n${getSchemaPartText( + err.parentSchema + )}`; + } else if (err.keyword === "instanceof") { + return `${dataPath} should be an instance of ${getSchemaPartText( + err.parentSchema + )}`; + } else if (err.keyword === "required") { + const missingProperty = err.params.missingProperty.replace(/^\./, ""); + return `${dataPath} misses the property '${missingProperty}'.\n${getSchemaPartText( + err.parentSchema, + ["properties", missingProperty] + )}`; + } else if (err.keyword === "minimum") { + return `${dataPath} ${err.message}.${getSchemaPartDescription( + err.parentSchema + )}`; + } else if (err.keyword === "uniqueItems") { + return `${dataPath} should not contain the item '${ + err.data[err.params.i] + }' twice.${getSchemaPartDescription(err.parentSchema)}`; + } else if ( + err.keyword === "minLength" || + err.keyword === "minItems" || + err.keyword === "minProperties" + ) { + if (err.params.limit === 1) { + return `${dataPath} should not be empty.${getSchemaPartDescription( + err.parentSchema + )}`; + } else { + return `${dataPath} ${err.message}${getSchemaPartDescription( + err.parentSchema + )}`; + } + } else if (err.keyword === "absolutePath") { + const baseMessage = `${dataPath}: ${ + err.message + }${getSchemaPartDescription(err.parentSchema)}`; + if (dataPath === "configuration.output.filename") { + return ( + `${baseMessage}\n` + + "Please use output.path to specify absolute path and output.filename for the file name." + ); + } + return baseMessage; + } else { + return `${dataPath} ${err.message} (${JSON.stringify( + err, + null, + 2 + )}).\n${getSchemaPartText(err.parentSchema)}`; + } + } +} + +module.exports = WebpackOptionsValidationError; diff --git a/node_modules/webpack/lib/compareLocations.js b/node_modules/webpack/lib/compareLocations.js index b8a4a118a..3840eb893 100644 --- a/node_modules/webpack/lib/compareLocations.js +++ b/node_modules/webpack/lib/compareLocations.js @@ -1,36 +1,52 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-module.exports = function compareLocations(a, b) {
- if(typeof a === "string") {
- if(typeof b === "string") {
- if(a < b) return -1;
- if(a > b) return 1;
- return 0;
- } else if(typeof b === "object") {
- return 1;
- } else {
- return 0;
- }
- } else if(typeof a === "object") {
- if(typeof b === "string") {
- return -1;
- } else if(typeof b === "object") {
- if(a.start && b.start) {
- const ap = a.start;
- const bp = b.start;
- if(ap.line < bp.line) return -1;
- if(ap.line > bp.line) return 1;
- if(ap.column < bp.column) return -1;
- if(ap.column > bp.column) return 1;
- }
- if(a.index < b.index) return -1;
- if(a.index > b.index) return 1;
- return 0;
- } else {
- return 0;
- }
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ + +// TODO webpack 5 remove string type from a and b +/** + * Compare two locations + * @param {string|DependencyLocation} a A location node + * @param {string|DependencyLocation} b A location node + * @returns {-1|0|1} sorting comparator value + */ +module.exports = (a, b) => { + if (typeof a === "string") { + if (typeof b === "string") { + if (a < b) return -1; + if (a > b) return 1; + return 0; + } else if (typeof b === "object") { + return 1; + } else { + return 0; + } + } else if (typeof a === "object") { + if (typeof b === "string") { + return -1; + } else if (typeof b === "object") { + if ("start" in a && "start" in b) { + const ap = a.start; + const bp = b.start; + if (ap.line < bp.line) return -1; + if (ap.line > bp.line) return 1; + if (ap.column < bp.column) return -1; + if (ap.column > bp.column) return 1; + } + if ("name" in a && "name" in b) { + if (a.name < b.name) return -1; + if (a.name > b.name) return 1; + } + if ("index" in a && "index" in b) { + if (a.index < b.index) return -1; + if (a.index > b.index) return 1; + } + return 0; + } else { + return 0; + } + } +}; diff --git a/node_modules/webpack/lib/dependencies/AMDDefineDependency.js b/node_modules/webpack/lib/dependencies/AMDDefineDependency.js index f290326e9..fcec365d5 100644 --- a/node_modules/webpack/lib/dependencies/AMDDefineDependency.js +++ b/node_modules/webpack/lib/dependencies/AMDDefineDependency.js @@ -1,142 +1,137 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const NullDependency = require("./NullDependency");
-
-class AMDDefineDependency extends NullDependency {
- constructor(range, arrayRange, functionRange, objectRange, namedModule) {
- super();
- this.range = range;
- this.arrayRange = arrayRange;
- this.functionRange = functionRange;
- this.objectRange = objectRange;
- this.namedModule = namedModule;
- }
-
- get type() {
- return "amd define";
- }
-}
-
-AMDDefineDependency.Template = class AMDDefineDependencyTemplate {
- get definitions() {
- return {
- f: [
- "var __WEBPACK_AMD_DEFINE_RESULT__;",
- `!(__WEBPACK_AMD_DEFINE_RESULT__ = (#).call(exports, __webpack_require__, exports, module),
- __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))`
- ],
- o: [
- "",
- "!(module.exports = #)"
- ],
- of: [
- "var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;",
- `!(__WEBPACK_AMD_DEFINE_FACTORY__ = (#),
- __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
- (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) :
- __WEBPACK_AMD_DEFINE_FACTORY__),
- __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))`
- ],
- af: [
- "var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;",
- `!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, __WEBPACK_AMD_DEFINE_RESULT__ = (#).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
- __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))`
- ],
- ao: [
- "",
- "!(#, module.exports = #)"
- ],
- aof: [
- "var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;",
- `!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, __WEBPACK_AMD_DEFINE_FACTORY__ = (#),
- __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
- (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
- __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))`
- ],
- lf: [
- "var XXX, XXXmodule;",
- "!(XXXmodule = { id: YYY, exports: {}, loaded: false }, XXX = #.call(XXXmodule.exports, __webpack_require__, XXXmodule.exports, XXXmodule), XXXmodule.loaded = true, XXX === undefined && (XXX = XXXmodule.exports))"
- ],
- lo: [
- "var XXX;",
- "!(XXX = #)"
- ],
- lof: [
- "var XXX, XXXfactory, XXXmodule;",
- "!(XXXfactory = (#), (XXXmodule = { id: YYY, exports: {}, loaded: false }), XXX = (typeof XXXfactory === 'function' ? (XXXfactory.call(XXXmodule.exports, __webpack_require__, XXXmodule.exports, XXXmodule)) : XXXfactory), (XXXmodule.loaded = true), XXX === undefined && (XXX = XXXmodule.exports))"
- ],
- laf: [
- "var __WEBPACK_AMD_DEFINE_ARRAY__, XXX;",
- "!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, XXX = ((#).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)))"
- ],
- lao: [
- "var XXX;",
- "!(#, XXX = #)"
- ],
- laof: [
- "var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_FACTORY__, XXX;",
- `!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, __WEBPACK_AMD_DEFINE_FACTORY__ = (#),
- XXX = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
- (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__))`
- ]
- };
- }
-
- apply(dependency, source) {
- const branch = this.branch(dependency);
- const defAndText = this.definitions[branch];
- const definitions = defAndText[0];
- const text = defAndText[1];
- this.replace(dependency, source, definitions, text);
- }
-
- localModuleVar(dependency) {
- return dependency.localModule && dependency.localModule.used && dependency.localModule.variableName();
- }
-
- branch(dependency) {
- const localModuleVar = this.localModuleVar(dependency) ? "l" : "";
- const arrayRange = dependency.arrayRange ? "a" : "";
- const objectRange = dependency.objectRange ? "o" : "";
- const functionRange = dependency.functionRange ? "f" : "";
- return localModuleVar + arrayRange + objectRange + functionRange;
- }
-
- replace(dependency, source, definition, text) {
- const localModuleVar = this.localModuleVar(dependency);
- if(localModuleVar) {
- text = text.replace(/XXX/g, localModuleVar.replace(/\$/g, "$$$$"));
- definition = definition.replace(/XXX/g, localModuleVar.replace(/\$/g, "$$$$"));
- }
-
- if(dependency.namedModule) {
- text = text.replace(/YYY/g, JSON.stringify(dependency.namedModule));
- }
-
- const texts = text.split("#");
-
- if(definition) source.insert(0, definition);
-
- let current = dependency.range[0];
- if(dependency.arrayRange) {
- source.replace(current, dependency.arrayRange[0] - 1, texts.shift());
- current = dependency.arrayRange[1];
- }
-
- if(dependency.objectRange) {
- source.replace(current, dependency.objectRange[0] - 1, texts.shift());
- current = dependency.objectRange[1];
- } else if(dependency.functionRange) {
- source.replace(current, dependency.functionRange[0] - 1, texts.shift());
- current = dependency.functionRange[1];
- }
- source.replace(current, dependency.range[1] - 1, texts.shift());
- if(texts.length > 0)
- throw new Error("Implementation error");
- }
-};
-
-module.exports = AMDDefineDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const NullDependency = require("./NullDependency"); + +class AMDDefineDependency extends NullDependency { + constructor(range, arrayRange, functionRange, objectRange, namedModule) { + super(); + this.range = range; + this.arrayRange = arrayRange; + this.functionRange = functionRange; + this.objectRange = objectRange; + this.namedModule = namedModule; + this.localModule = null; + } + + get type() { + return "amd define"; + } +} + +AMDDefineDependency.Template = class AMDDefineDependencyTemplate { + get definitions() { + return { + f: [ + "var __WEBPACK_AMD_DEFINE_RESULT__;", + `!(__WEBPACK_AMD_DEFINE_RESULT__ = (#).call(exports, __webpack_require__, exports, module), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))` + ], + o: ["", "!(module.exports = #)"], + of: [ + "var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;", + `!(__WEBPACK_AMD_DEFINE_FACTORY__ = (#), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : + __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))` + ], + af: [ + "var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;", + `!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, __WEBPACK_AMD_DEFINE_RESULT__ = (#).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))` + ], + ao: ["", "!(#, module.exports = #)"], + aof: [ + "var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;", + `!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, __WEBPACK_AMD_DEFINE_FACTORY__ = (#), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))` + ], + lf: [ + "var XXX, XXXmodule;", + "!(XXXmodule = { id: YYY, exports: {}, loaded: false }, XXX = #.call(XXXmodule.exports, __webpack_require__, XXXmodule.exports, XXXmodule), XXXmodule.loaded = true, XXX === undefined && (XXX = XXXmodule.exports))" + ], + lo: ["var XXX;", "!(XXX = #)"], + lof: [ + "var XXX, XXXfactory, XXXmodule;", + "!(XXXfactory = (#), (XXXmodule = { id: YYY, exports: {}, loaded: false }), XXX = (typeof XXXfactory === 'function' ? (XXXfactory.call(XXXmodule.exports, __webpack_require__, XXXmodule.exports, XXXmodule)) : XXXfactory), (XXXmodule.loaded = true), XXX === undefined && (XXX = XXXmodule.exports))" + ], + laf: [ + "var __WEBPACK_AMD_DEFINE_ARRAY__, XXX;", + "!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, XXX = ((#).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)))" + ], + lao: ["var XXX;", "!(#, XXX = #)"], + laof: [ + "var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_FACTORY__, XXX;", + `!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, __WEBPACK_AMD_DEFINE_FACTORY__ = (#), + XXX = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__))` + ] + }; + } + + apply(dependency, source) { + const branch = this.branch(dependency); + const defAndText = this.definitions[branch]; + const definitions = defAndText[0]; + const text = defAndText[1]; + this.replace(dependency, source, definitions, text); + } + + localModuleVar(dependency) { + return ( + dependency.localModule && + dependency.localModule.used && + dependency.localModule.variableName() + ); + } + + branch(dependency) { + const localModuleVar = this.localModuleVar(dependency) ? "l" : ""; + const arrayRange = dependency.arrayRange ? "a" : ""; + const objectRange = dependency.objectRange ? "o" : ""; + const functionRange = dependency.functionRange ? "f" : ""; + return localModuleVar + arrayRange + objectRange + functionRange; + } + + replace(dependency, source, definition, text) { + const localModuleVar = this.localModuleVar(dependency); + if (localModuleVar) { + text = text.replace(/XXX/g, localModuleVar.replace(/\$/g, "$$$$")); + definition = definition.replace( + /XXX/g, + localModuleVar.replace(/\$/g, "$$$$") + ); + } + + if (dependency.namedModule) { + text = text.replace(/YYY/g, JSON.stringify(dependency.namedModule)); + } + + const texts = text.split("#"); + + if (definition) source.insert(0, definition); + + let current = dependency.range[0]; + if (dependency.arrayRange) { + source.replace(current, dependency.arrayRange[0] - 1, texts.shift()); + current = dependency.arrayRange[1]; + } + + if (dependency.objectRange) { + source.replace(current, dependency.objectRange[0] - 1, texts.shift()); + current = dependency.objectRange[1]; + } else if (dependency.functionRange) { + source.replace(current, dependency.functionRange[0] - 1, texts.shift()); + current = dependency.functionRange[1]; + } + source.replace(current, dependency.range[1] - 1, texts.shift()); + if (texts.length > 0) throw new Error("Implementation error"); + } +}; + +module.exports = AMDDefineDependency; diff --git a/node_modules/webpack/lib/dependencies/AMDDefineDependencyParserPlugin.js b/node_modules/webpack/lib/dependencies/AMDDefineDependencyParserPlugin.js index 227f68d36..95e862d12 100644 --- a/node_modules/webpack/lib/dependencies/AMDDefineDependencyParserPlugin.js +++ b/node_modules/webpack/lib/dependencies/AMDDefineDependencyParserPlugin.js @@ -1,266 +1,334 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const AMDRequireItemDependency = require("./AMDRequireItemDependency");
-const AMDRequireContextDependency = require("./AMDRequireContextDependency");
-const ConstDependency = require("./ConstDependency");
-const AMDDefineDependency = require("./AMDDefineDependency");
-const AMDRequireArrayDependency = require("./AMDRequireArrayDependency");
-const LocalModuleDependency = require("./LocalModuleDependency");
-const ContextDependencyHelpers = require("./ContextDependencyHelpers");
-const LocalModulesHelpers = require("./LocalModulesHelpers");
-
-function isBoundFunctionExpression(expr) {
- if(expr.type !== "CallExpression") return false;
- if(expr.callee.type !== "MemberExpression") return false;
- if(expr.callee.computed) return false;
- if(expr.callee.object.type !== "FunctionExpression") return false;
- if(expr.callee.property.type !== "Identifier") return false;
- if(expr.callee.property.name !== "bind") return false;
- return true;
-}
-
-function isUnboundFunctionExpression(expr) {
- if(expr.type === "FunctionExpression") return true;
- if(expr.type === "ArrowFunctionExpression") return true;
- return false;
-}
-
-function isCallable(expr) {
- if(isUnboundFunctionExpression(expr)) return true;
- if(isBoundFunctionExpression(expr)) return true;
- return false;
-}
-
-class AMDDefineDependencyParserPlugin {
- constructor(options) {
- this.options = options;
- }
-
- newDefineDependency(range, arrayRange, functionRange, objectRange, namedModule) {
- return new AMDDefineDependency(range, arrayRange, functionRange, objectRange, namedModule);
- }
-
- apply(parser) {
- const options = this.options;
- parser.plugin("call define", (expr) => {
- let array, fn, obj, namedModule;
- switch(expr.arguments.length) {
- case 1:
- if(isCallable(expr.arguments[0])) {
- // define(f() {...})
- fn = expr.arguments[0];
- } else if(expr.arguments[0].type === "ObjectExpression") {
- // define({...})
- obj = expr.arguments[0];
- } else {
- // define(expr)
- // unclear if function or object
- obj = fn = expr.arguments[0];
- }
- break;
- case 2:
- if(expr.arguments[0].type === "Literal") {
- namedModule = expr.arguments[0].value;
- // define("...", ...)
- if(isCallable(expr.arguments[1])) {
- // define("...", f() {...})
- fn = expr.arguments[1];
- } else if(expr.arguments[1].type === "ObjectExpression") {
- // define("...", {...})
- obj = expr.arguments[1];
- } else {
- // define("...", expr)
- // unclear if function or object
- obj = fn = expr.arguments[1];
- }
- } else {
- array = expr.arguments[0];
- if(isCallable(expr.arguments[1])) {
- // define([...], f() {})
- fn = expr.arguments[1];
- } else if(expr.arguments[1].type === "ObjectExpression") {
- // define([...], {...})
- obj = expr.arguments[1];
- } else {
- // define([...], expr)
- // unclear if function or object
- obj = fn = expr.arguments[1];
- }
- }
- break;
- case 3:
- // define("...", [...], f() {...})
- namedModule = expr.arguments[0].value;
- array = expr.arguments[1];
- if(isCallable(expr.arguments[2])) {
- // define("...", [...], f() {})
- fn = expr.arguments[2];
- } else if(expr.arguments[2].type === "ObjectExpression") {
- // define("...", [...], {...})
- obj = expr.arguments[2];
- } else {
- // define("...", [...], expr)
- // unclear if function or object
- obj = fn = expr.arguments[2];
- }
- break;
- default:
- return;
- }
- let fnParams = null;
- let fnParamsOffset = 0;
- if(fn) {
- if(isUnboundFunctionExpression(fn)) fnParams = fn.params;
- else if(isBoundFunctionExpression(fn)) {
- fnParams = fn.callee.object.params;
- fnParamsOffset = fn.arguments.length - 1;
- if(fnParamsOffset < 0) fnParamsOffset = 0;
- }
- }
- let fnRenames = Object.create(parser.scope.renames);
- let identifiers;
- if(array) {
- identifiers = {};
- const param = parser.evaluateExpression(array);
- const result = parser.applyPluginsBailResult("call define:amd:array", expr, param, identifiers, namedModule);
- if(!result) return;
- if(fnParams) fnParams = fnParams.slice(fnParamsOffset).filter((param, idx) => {
- if(identifiers[idx]) {
- fnRenames["$" + param.name] = identifiers[idx];
- return false;
- }
- return true;
- });
- } else {
- identifiers = ["require", "exports", "module"];
- if(fnParams) fnParams = fnParams.slice(fnParamsOffset).filter((param, idx) => {
- if(identifiers[idx]) {
- fnRenames["$" + param.name] = identifiers[idx];
- return false;
- }
- return true;
- });
- }
- let inTry;
- if(fn && isUnboundFunctionExpression(fn)) {
- inTry = parser.scope.inTry;
- parser.inScope(fnParams, () => {
- parser.scope.renames = fnRenames;
- parser.scope.inTry = inTry;
- if(fn.body.type === "BlockStatement")
- parser.walkStatement(fn.body);
- else
- parser.walkExpression(fn.body);
- });
- } else if(fn && isBoundFunctionExpression(fn)) {
- inTry = parser.scope.inTry;
- parser.inScope(fn.callee.object.params.filter((i) => ["require", "module", "exports"].indexOf(i.name) < 0), () => {
- parser.scope.renames = fnRenames;
- parser.scope.inTry = inTry;
- if(fn.callee.object.body.type === "BlockStatement")
- parser.walkStatement(fn.callee.object.body);
- else
- parser.walkExpression(fn.callee.object.body);
- });
- if(fn.arguments)
- parser.walkExpressions(fn.arguments);
- } else if(fn || obj) {
- parser.walkExpression(fn || obj);
- }
-
- const dep = this.newDefineDependency(
- expr.range,
- array ? array.range : null,
- fn ? fn.range : null,
- obj ? obj.range : null,
- namedModule ? namedModule : null
- );
- dep.loc = expr.loc;
- if(namedModule) {
- dep.localModule = LocalModulesHelpers.addLocalModule(parser.state, namedModule);
- }
- parser.state.current.addDependency(dep);
- return true;
- });
- parser.plugin("call define:amd:array", (expr, param, identifiers, namedModule) => {
- if(param.isArray()) {
- param.items.forEach((param, idx) => {
- if(param.isString() && ["require", "module", "exports"].indexOf(param.string) >= 0)
- identifiers[idx] = param.string;
- const result = parser.applyPluginsBailResult("call define:amd:item", expr, param, namedModule);
- if(result === undefined) {
- parser.applyPluginsBailResult("call define:amd:context", expr, param);
- }
- });
- return true;
- } else if(param.isConstArray()) {
- const deps = [];
- param.array.forEach((request, idx) => {
- let dep;
- let localModule;
- if(request === "require") {
- identifiers[idx] = request;
- dep = "__webpack_require__";
- } else if(["exports", "module"].indexOf(request) >= 0) {
- identifiers[idx] = request;
- dep = request;
- } else if(localModule = LocalModulesHelpers.getLocalModule(parser.state, request)) { // eslint-disable-line no-cond-assign
- dep = new LocalModuleDependency(localModule);
- dep.loc = expr.loc;
- parser.state.current.addDependency(dep);
- } else {
- dep = new AMDRequireItemDependency(request);
- dep.loc = expr.loc;
- dep.optional = !!parser.scope.inTry;
- parser.state.current.addDependency(dep);
- }
- deps.push(dep);
- });
- const dep = new AMDRequireArrayDependency(deps, param.range);
- dep.loc = expr.loc;
- dep.optional = !!parser.scope.inTry;
- parser.state.current.addDependency(dep);
- return true;
- }
- });
- parser.plugin("call define:amd:item", (expr, param, namedModule) => {
- if(param.isConditional()) {
- param.options.forEach((param) => {
- const result = parser.applyPluginsBailResult("call define:amd:item", expr, param);
- if(result === undefined) {
- parser.applyPluginsBailResult("call define:amd:context", expr, param);
- }
- });
- return true;
- } else if(param.isString()) {
- let dep, localModule;
- if(param.string === "require") {
- dep = new ConstDependency("__webpack_require__", param.range);
- } else if(["require", "exports", "module"].indexOf(param.string) >= 0) {
- dep = new ConstDependency(param.string, param.range);
- } else if(localModule = LocalModulesHelpers.getLocalModule(parser.state, param.string, namedModule)) { // eslint-disable-line no-cond-assign
- dep = new LocalModuleDependency(localModule, param.range);
- } else {
- dep = new AMDRequireItemDependency(param.string, param.range);
- }
- dep.loc = expr.loc;
- dep.optional = !!parser.scope.inTry;
- parser.state.current.addDependency(dep);
- return true;
- }
- });
- parser.plugin("call define:amd:context", (expr, param) => {
- const dep = ContextDependencyHelpers.create(AMDRequireContextDependency, param.range, param, expr, options);
- if(!dep) return;
- dep.loc = expr.loc;
- dep.optional = !!parser.scope.inTry;
- parser.state.current.addDependency(dep);
- return true;
- });
- }
-}
-module.exports = AMDDefineDependencyParserPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const AMDRequireItemDependency = require("./AMDRequireItemDependency"); +const AMDRequireContextDependency = require("./AMDRequireContextDependency"); +const ConstDependency = require("./ConstDependency"); +const AMDDefineDependency = require("./AMDDefineDependency"); +const AMDRequireArrayDependency = require("./AMDRequireArrayDependency"); +const LocalModuleDependency = require("./LocalModuleDependency"); +const ContextDependencyHelpers = require("./ContextDependencyHelpers"); +const LocalModulesHelpers = require("./LocalModulesHelpers"); + +const isBoundFunctionExpression = expr => { + if (expr.type !== "CallExpression") return false; + if (expr.callee.type !== "MemberExpression") return false; + if (expr.callee.computed) return false; + if (expr.callee.object.type !== "FunctionExpression") return false; + if (expr.callee.property.type !== "Identifier") return false; + if (expr.callee.property.name !== "bind") return false; + return true; +}; + +const isUnboundFunctionExpression = expr => { + if (expr.type === "FunctionExpression") return true; + if (expr.type === "ArrowFunctionExpression") return true; + return false; +}; + +const isCallable = expr => { + if (isUnboundFunctionExpression(expr)) return true; + if (isBoundFunctionExpression(expr)) return true; + return false; +}; + +class AMDDefineDependencyParserPlugin { + constructor(options) { + this.options = options; + } + + apply(parser) { + parser.hooks.call + .for("define") + .tap( + "AMDDefineDependencyParserPlugin", + this.processCallDefine.bind(this, parser) + ); + } + + processArray(parser, expr, param, identifiers, namedModule) { + if (param.isArray()) { + param.items.forEach((param, idx) => { + if ( + param.isString() && + ["require", "module", "exports"].includes(param.string) + ) + identifiers[idx] = param.string; + const result = this.processItem(parser, expr, param, namedModule); + if (result === undefined) { + this.processContext(parser, expr, param); + } + }); + return true; + } else if (param.isConstArray()) { + const deps = []; + param.array.forEach((request, idx) => { + let dep; + let localModule; + if (request === "require") { + identifiers[idx] = request; + dep = "__webpack_require__"; + } else if (["exports", "module"].includes(request)) { + identifiers[idx] = request; + dep = request; + } else if ( + (localModule = LocalModulesHelpers.getLocalModule( + parser.state, + request + )) + ) { + dep = new LocalModuleDependency(localModule, undefined, false); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + } else { + dep = this.newRequireItemDependency(request); + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + } + deps.push(dep); + }); + const dep = this.newRequireArrayDependency(deps, param.range); + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + } + } + processItem(parser, expr, param, namedModule) { + if (param.isConditional()) { + param.options.forEach(param => { + const result = this.processItem(parser, expr, param); + if (result === undefined) { + this.processContext(parser, expr, param); + } + }); + return true; + } else if (param.isString()) { + let dep, localModule; + if (param.string === "require") { + dep = new ConstDependency("__webpack_require__", param.range); + } else if (["require", "exports", "module"].includes(param.string)) { + dep = new ConstDependency(param.string, param.range); + } else if ( + (localModule = LocalModulesHelpers.getLocalModule( + parser.state, + param.string, + namedModule + )) + ) { + dep = new LocalModuleDependency(localModule, param.range, false); + } else { + dep = this.newRequireItemDependency(param.string, param.range); + } + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + } + } + processContext(parser, expr, param) { + const dep = ContextDependencyHelpers.create( + AMDRequireContextDependency, + param.range, + param, + expr, + this.options + ); + if (!dep) return; + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + } + + processCallDefine(parser, expr) { + let array, fn, obj, namedModule; + switch (expr.arguments.length) { + case 1: + if (isCallable(expr.arguments[0])) { + // define(f() {…}) + fn = expr.arguments[0]; + } else if (expr.arguments[0].type === "ObjectExpression") { + // define({…}) + obj = expr.arguments[0]; + } else { + // define(expr) + // unclear if function or object + obj = fn = expr.arguments[0]; + } + break; + case 2: + if (expr.arguments[0].type === "Literal") { + namedModule = expr.arguments[0].value; + // define("…", …) + if (isCallable(expr.arguments[1])) { + // define("…", f() {…}) + fn = expr.arguments[1]; + } else if (expr.arguments[1].type === "ObjectExpression") { + // define("…", {…}) + obj = expr.arguments[1]; + } else { + // define("…", expr) + // unclear if function or object + obj = fn = expr.arguments[1]; + } + } else { + array = expr.arguments[0]; + if (isCallable(expr.arguments[1])) { + // define([…], f() {}) + fn = expr.arguments[1]; + } else if (expr.arguments[1].type === "ObjectExpression") { + // define([…], {…}) + obj = expr.arguments[1]; + } else { + // define([…], expr) + // unclear if function or object + obj = fn = expr.arguments[1]; + } + } + break; + case 3: + // define("…", […], f() {…}) + namedModule = expr.arguments[0].value; + array = expr.arguments[1]; + if (isCallable(expr.arguments[2])) { + // define("…", […], f() {}) + fn = expr.arguments[2]; + } else if (expr.arguments[2].type === "ObjectExpression") { + // define("…", […], {…}) + obj = expr.arguments[2]; + } else { + // define("…", […], expr) + // unclear if function or object + obj = fn = expr.arguments[2]; + } + break; + default: + return; + } + let fnParams = null; + let fnParamsOffset = 0; + if (fn) { + if (isUnboundFunctionExpression(fn)) { + fnParams = fn.params; + } else if (isBoundFunctionExpression(fn)) { + fnParams = fn.callee.object.params; + fnParamsOffset = fn.arguments.length - 1; + if (fnParamsOffset < 0) { + fnParamsOffset = 0; + } + } + } + let fnRenames = parser.scope.renames.createChild(); + if (array) { + const identifiers = {}; + const param = parser.evaluateExpression(array); + const result = this.processArray( + parser, + expr, + param, + identifiers, + namedModule + ); + if (!result) return; + if (fnParams) { + fnParams = fnParams.slice(fnParamsOffset).filter((param, idx) => { + if (identifiers[idx]) { + fnRenames.set(param.name, identifiers[idx]); + return false; + } + return true; + }); + } + } else { + const identifiers = ["require", "exports", "module"]; + if (fnParams) { + fnParams = fnParams.slice(fnParamsOffset).filter((param, idx) => { + if (identifiers[idx]) { + fnRenames.set(param.name, identifiers[idx]); + return false; + } + return true; + }); + } + } + let inTry; + if (fn && isUnboundFunctionExpression(fn)) { + inTry = parser.scope.inTry; + parser.inScope(fnParams, () => { + parser.scope.renames = fnRenames; + parser.scope.inTry = inTry; + if (fn.body.type === "BlockStatement") { + parser.walkStatement(fn.body); + } else { + parser.walkExpression(fn.body); + } + }); + } else if (fn && isBoundFunctionExpression(fn)) { + inTry = parser.scope.inTry; + parser.inScope( + fn.callee.object.params.filter( + i => !["require", "module", "exports"].includes(i.name) + ), + () => { + parser.scope.renames = fnRenames; + parser.scope.inTry = inTry; + if (fn.callee.object.body.type === "BlockStatement") { + parser.walkStatement(fn.callee.object.body); + } else { + parser.walkExpression(fn.callee.object.body); + } + } + ); + if (fn.arguments) { + parser.walkExpressions(fn.arguments); + } + } else if (fn || obj) { + parser.walkExpression(fn || obj); + } + + const dep = this.newDefineDependency( + expr.range, + array ? array.range : null, + fn ? fn.range : null, + obj ? obj.range : null, + namedModule ? namedModule : null + ); + dep.loc = expr.loc; + if (namedModule) { + dep.localModule = LocalModulesHelpers.addLocalModule( + parser.state, + namedModule + ); + } + parser.state.current.addDependency(dep); + return true; + } + + newDefineDependency( + range, + arrayRange, + functionRange, + objectRange, + namedModule + ) { + return new AMDDefineDependency( + range, + arrayRange, + functionRange, + objectRange, + namedModule + ); + } + newRequireArrayDependency(depsArray, range) { + return new AMDRequireArrayDependency(depsArray, range); + } + newRequireItemDependency(request, range) { + return new AMDRequireItemDependency(request, range); + } +} +module.exports = AMDDefineDependencyParserPlugin; diff --git a/node_modules/webpack/lib/dependencies/AMDPlugin.js b/node_modules/webpack/lib/dependencies/AMDPlugin.js index 944241c23..d113491c9 100644 --- a/node_modules/webpack/lib/dependencies/AMDPlugin.js +++ b/node_modules/webpack/lib/dependencies/AMDPlugin.js @@ -1,119 +1,249 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const path = require("path");
-const AMDRequireDependency = require("./AMDRequireDependency");
-const AMDRequireItemDependency = require("./AMDRequireItemDependency");
-const AMDRequireArrayDependency = require("./AMDRequireArrayDependency");
-const AMDRequireContextDependency = require("./AMDRequireContextDependency");
-const AMDDefineDependency = require("./AMDDefineDependency");
-const UnsupportedDependency = require("./UnsupportedDependency");
-const LocalModuleDependency = require("./LocalModuleDependency");
-
-const NullFactory = require("../NullFactory");
-
-const AMDRequireDependenciesBlockParserPlugin = require("./AMDRequireDependenciesBlockParserPlugin");
-const AMDDefineDependencyParserPlugin = require("./AMDDefineDependencyParserPlugin");
-
-const AliasPlugin = require("enhanced-resolve/lib/AliasPlugin");
-
-const ParserHelpers = require("../ParserHelpers");
-
-class AMDPlugin {
- constructor(options, amdOptions) {
- this.amdOptions = amdOptions;
- this.options = options;
- }
-
- apply(compiler) {
- const options = this.options;
- const amdOptions = this.amdOptions;
- compiler.plugin("compilation", (compilation, params) => {
- const normalModuleFactory = params.normalModuleFactory;
- const contextModuleFactory = params.contextModuleFactory;
-
- compilation.dependencyFactories.set(AMDRequireDependency, new NullFactory());
- compilation.dependencyTemplates.set(AMDRequireDependency, new AMDRequireDependency.Template());
-
- compilation.dependencyFactories.set(AMDRequireItemDependency, normalModuleFactory);
- compilation.dependencyTemplates.set(AMDRequireItemDependency, new AMDRequireItemDependency.Template());
-
- compilation.dependencyFactories.set(AMDRequireArrayDependency, new NullFactory());
- compilation.dependencyTemplates.set(AMDRequireArrayDependency, new AMDRequireArrayDependency.Template());
-
- compilation.dependencyFactories.set(AMDRequireContextDependency, contextModuleFactory);
- compilation.dependencyTemplates.set(AMDRequireContextDependency, new AMDRequireContextDependency.Template());
-
- compilation.dependencyFactories.set(AMDDefineDependency, new NullFactory());
- compilation.dependencyTemplates.set(AMDDefineDependency, new AMDDefineDependency.Template());
-
- compilation.dependencyFactories.set(UnsupportedDependency, new NullFactory());
- compilation.dependencyTemplates.set(UnsupportedDependency, new UnsupportedDependency.Template());
-
- compilation.dependencyFactories.set(LocalModuleDependency, new NullFactory());
- compilation.dependencyTemplates.set(LocalModuleDependency, new LocalModuleDependency.Template());
-
- params.normalModuleFactory.plugin("parser", (parser, parserOptions) => {
-
- if(typeof parserOptions.amd !== "undefined" && !parserOptions.amd)
- return;
-
- function setExpressionToModule(outerExpr, module) {
- parser.plugin("expression " + outerExpr, (expr) => {
- const dep = new AMDRequireItemDependency(module, expr.range);
- dep.userRequest = outerExpr;
- dep.loc = expr.loc;
- parser.state.current.addDependency(dep);
- return true;
- });
- }
-
- parser.apply(
- new AMDRequireDependenciesBlockParserPlugin(options),
- new AMDDefineDependencyParserPlugin(options)
- );
- setExpressionToModule("require.amd", "!!webpack amd options");
- setExpressionToModule("define.amd", "!!webpack amd options");
- setExpressionToModule("define", "!!webpack amd define");
- parser.plugin("expression __webpack_amd_options__", () =>
- parser.state.current.addVariable("__webpack_amd_options__", JSON.stringify(amdOptions)));
- parser.plugin("evaluate typeof define.amd", ParserHelpers.evaluateToString(typeof amdOptions));
- parser.plugin("evaluate typeof require.amd", ParserHelpers.evaluateToString(typeof amdOptions));
- parser.plugin("evaluate Identifier define.amd", ParserHelpers.evaluateToIdentifier("define.amd", true));
- parser.plugin("evaluate Identifier require.amd", ParserHelpers.evaluateToIdentifier("require.amd", true));
- parser.plugin("typeof define", ParserHelpers.toConstantDependency(JSON.stringify("function")));
- parser.plugin("evaluate typeof define", ParserHelpers.evaluateToString("function"));
- parser.plugin("can-rename define", ParserHelpers.approve);
- parser.plugin("rename define", (expr) => {
- const dep = new AMDRequireItemDependency("!!webpack amd define", expr.range);
- dep.userRequest = "define";
- dep.loc = expr.loc;
- parser.state.current.addDependency(dep);
- return false;
- });
- parser.plugin("typeof require", ParserHelpers.toConstantDependency(JSON.stringify("function")));
- parser.plugin("evaluate typeof require", ParserHelpers.evaluateToString("function"));
- });
- });
- compiler.plugin("after-resolvers", () => {
- compiler.resolvers.normal.apply(
- new AliasPlugin("described-resolve", {
- name: "amdefine",
- alias: path.join(__dirname, "..", "..", "buildin", "amd-define.js")
- }, "resolve"),
- new AliasPlugin("described-resolve", {
- name: "webpack amd options",
- alias: path.join(__dirname, "..", "..", "buildin", "amd-options.js")
- }, "resolve"),
- new AliasPlugin("described-resolve", {
- name: "webpack amd define",
- alias: path.join(__dirname, "..", "..", "buildin", "amd-define.js")
- }, "resolve")
- );
- });
- }
-}
-module.exports = AMDPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const path = require("path"); +const AMDRequireDependency = require("./AMDRequireDependency"); +const AMDRequireItemDependency = require("./AMDRequireItemDependency"); +const AMDRequireArrayDependency = require("./AMDRequireArrayDependency"); +const AMDRequireContextDependency = require("./AMDRequireContextDependency"); +const AMDDefineDependency = require("./AMDDefineDependency"); +const UnsupportedDependency = require("./UnsupportedDependency"); +const LocalModuleDependency = require("./LocalModuleDependency"); + +const NullFactory = require("../NullFactory"); + +const AMDRequireDependenciesBlockParserPlugin = require("./AMDRequireDependenciesBlockParserPlugin"); +const AMDDefineDependencyParserPlugin = require("./AMDDefineDependencyParserPlugin"); + +const AliasPlugin = require("enhanced-resolve/lib/AliasPlugin"); + +const ParserHelpers = require("../ParserHelpers"); + +class AMDPlugin { + constructor(options, amdOptions) { + this.amdOptions = amdOptions; + this.options = options; + } + + apply(compiler) { + const options = this.options; + const amdOptions = this.amdOptions; + compiler.hooks.compilation.tap( + "AMDPlugin", + (compilation, { contextModuleFactory, normalModuleFactory }) => { + compilation.dependencyFactories.set( + AMDRequireDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + AMDRequireDependency, + new AMDRequireDependency.Template() + ); + + compilation.dependencyFactories.set( + AMDRequireItemDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + AMDRequireItemDependency, + new AMDRequireItemDependency.Template() + ); + + compilation.dependencyFactories.set( + AMDRequireArrayDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + AMDRequireArrayDependency, + new AMDRequireArrayDependency.Template() + ); + + compilation.dependencyFactories.set( + AMDRequireContextDependency, + contextModuleFactory + ); + compilation.dependencyTemplates.set( + AMDRequireContextDependency, + new AMDRequireContextDependency.Template() + ); + + compilation.dependencyFactories.set( + AMDDefineDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + AMDDefineDependency, + new AMDDefineDependency.Template() + ); + + compilation.dependencyFactories.set( + UnsupportedDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + UnsupportedDependency, + new UnsupportedDependency.Template() + ); + + compilation.dependencyFactories.set( + LocalModuleDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + LocalModuleDependency, + new LocalModuleDependency.Template() + ); + + const handler = (parser, parserOptions) => { + if (parserOptions.amd !== undefined && !parserOptions.amd) return; + + const setExpressionToModule = (outerExpr, module) => { + parser.hooks.expression.for(outerExpr).tap("AMDPlugin", expr => { + const dep = new AMDRequireItemDependency(module, expr.range); + dep.userRequest = outerExpr; + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + return true; + }); + }; + + new AMDRequireDependenciesBlockParserPlugin(options).apply(parser); + new AMDDefineDependencyParserPlugin(options).apply(parser); + + setExpressionToModule("require.amd", "!!webpack amd options"); + setExpressionToModule("define.amd", "!!webpack amd options"); + setExpressionToModule("define", "!!webpack amd define"); + + parser.hooks.expression + .for("__webpack_amd_options__") + .tap("AMDPlugin", () => + parser.state.current.addVariable( + "__webpack_amd_options__", + JSON.stringify(amdOptions) + ) + ); + parser.hooks.evaluateTypeof + .for("define.amd") + .tap( + "AMDPlugin", + ParserHelpers.evaluateToString(typeof amdOptions) + ); + parser.hooks.evaluateTypeof + .for("require.amd") + .tap( + "AMDPlugin", + ParserHelpers.evaluateToString(typeof amdOptions) + ); + parser.hooks.evaluateIdentifier + .for("define.amd") + .tap( + "AMDPlugin", + ParserHelpers.evaluateToIdentifier("define.amd", true) + ); + parser.hooks.evaluateIdentifier + .for("require.amd") + .tap( + "AMDPlugin", + ParserHelpers.evaluateToIdentifier("require.amd", true) + ); + parser.hooks.typeof + .for("define") + .tap( + "AMDPlugin", + ParserHelpers.toConstantDependency( + parser, + JSON.stringify("function") + ) + ); + parser.hooks.evaluateTypeof + .for("define") + .tap("AMDPlugin", ParserHelpers.evaluateToString("function")); + parser.hooks.canRename + .for("define") + .tap("AMDPlugin", ParserHelpers.approve); + parser.hooks.rename.for("define").tap("AMDPlugin", expr => { + const dep = new AMDRequireItemDependency( + "!!webpack amd define", + expr.range + ); + dep.userRequest = "define"; + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + return false; + }); + parser.hooks.typeof + .for("require") + .tap( + "AMDPlugin", + ParserHelpers.toConstantDependency( + parser, + JSON.stringify("function") + ) + ); + parser.hooks.evaluateTypeof + .for("require") + .tap("AMDPlugin", ParserHelpers.evaluateToString("function")); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("AMDPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("AMDPlugin", handler); + } + ); + compiler.hooks.afterResolvers.tap("AMDPlugin", () => { + compiler.resolverFactory.hooks.resolver + .for("normal") + .tap("AMDPlugin", resolver => { + new AliasPlugin( + "described-resolve", + { + name: "amdefine", + alias: path.join( + __dirname, + "..", + "..", + "buildin", + "amd-define.js" + ) + }, + "resolve" + ).apply(resolver); + new AliasPlugin( + "described-resolve", + { + name: "webpack amd options", + alias: path.join( + __dirname, + "..", + "..", + "buildin", + "amd-options.js" + ) + }, + "resolve" + ).apply(resolver); + new AliasPlugin( + "described-resolve", + { + name: "webpack amd define", + alias: path.join( + __dirname, + "..", + "..", + "buildin", + "amd-define.js" + ) + }, + "resolve" + ).apply(resolver); + }); + }); + } +} +module.exports = AMDPlugin; diff --git a/node_modules/webpack/lib/dependencies/AMDRequireArrayDependency.js b/node_modules/webpack/lib/dependencies/AMDRequireArrayDependency.js index ad77b0705..ddb9c293f 100644 --- a/node_modules/webpack/lib/dependencies/AMDRequireArrayDependency.js +++ b/node_modules/webpack/lib/dependencies/AMDRequireArrayDependency.js @@ -1,58 +1,49 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const Dependency = require("../Dependency");
-const webpackMissingModuleModule = require("./WebpackMissingModule").module;
-
-class AMDRequireArrayDependency extends Dependency {
- constructor(depsArray, range) {
- super();
- this.depsArray = depsArray;
- this.range = range;
- }
-
- get type() {
- return "amd require array";
- }
-}
-
-AMDRequireArrayDependency.Template = class AMDRequireArrayDependencyTemplate {
- apply(dep, source, outputOptions, requestShortener) {
- const content = this.getContent(dep, outputOptions, requestShortener);
- source.replace(dep.range[0], dep.range[1] - 1, content);
- }
-
- getContent(dep, outputOptions, requestShortener) {
- const requires = dep.depsArray.map((dependency) => {
- const optionalComment = this.optionalComment(outputOptions.pathinfo, requestShortener.shorten(dependency.request));
- return this.contentForDependency(dependency, optionalComment);
- });
- return `[${requires.join(", ")}]`;
- }
-
- optionalComment(pathInfo, shortenedRequest) {
- if(!pathInfo) {
- return "";
- }
- return `/*! ${shortenedRequest} */ `;
- }
-
- contentForDependency(dep, comment) {
- if(typeof dep === "string") {
- return dep;
- }
-
- if(dep.module) {
- const stringifiedId = JSON.stringify(dep.module.id);
- return `__webpack_require__(${comment}${stringifiedId})`;
- } else if(dep.localModule) {
- return dep.localModule.variableName();
- }
-
- return webpackMissingModuleModule(dep.request);
- }
-};
-
-module.exports = AMDRequireArrayDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const Dependency = require("../Dependency"); + +class AMDRequireArrayDependency extends Dependency { + constructor(depsArray, range) { + super(); + this.depsArray = depsArray; + this.range = range; + } + + get type() { + return "amd require array"; + } +} + +AMDRequireArrayDependency.Template = class AMDRequireArrayDependencyTemplate { + apply(dep, source, runtime) { + const content = this.getContent(dep, runtime); + source.replace(dep.range[0], dep.range[1] - 1, content); + } + + getContent(dep, runtime) { + const requires = dep.depsArray.map(dependency => { + return this.contentForDependency(dependency, runtime); + }); + return `[${requires.join(", ")}]`; + } + + contentForDependency(dep, runtime) { + if (typeof dep === "string") { + return dep; + } + + if (dep.localModule) { + return dep.localModule.variableName(); + } else { + return runtime.moduleExports({ + module: dep.module, + request: dep.request + }); + } + } +}; + +module.exports = AMDRequireArrayDependency; diff --git a/node_modules/webpack/lib/dependencies/AMDRequireContextDependency.js b/node_modules/webpack/lib/dependencies/AMDRequireContextDependency.js index 5305288cf..b2e60b5b9 100644 --- a/node_modules/webpack/lib/dependencies/AMDRequireContextDependency.js +++ b/node_modules/webpack/lib/dependencies/AMDRequireContextDependency.js @@ -1,20 +1,20 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const ContextDependency = require("./ContextDependency");
-class AMDRequireContextDependency extends ContextDependency {
- constructor(request, recursive, regExp, range, valueRange) {
- super(request, recursive, regExp);
- this.range = range;
- this.valueRange = valueRange;
- }
-
- get type() {
- return "amd require context";
- }
-}
-AMDRequireContextDependency.Template = require("./ContextDependencyTemplateAsRequireCall");
-module.exports = AMDRequireContextDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const ContextDependency = require("./ContextDependency"); +class AMDRequireContextDependency extends ContextDependency { + constructor(options, range, valueRange) { + super(options); + this.range = range; + this.valueRange = valueRange; + } + + get type() { + return "amd require context"; + } +} +AMDRequireContextDependency.Template = require("./ContextDependencyTemplateAsRequireCall"); +module.exports = AMDRequireContextDependency; diff --git a/node_modules/webpack/lib/dependencies/AMDRequireDependenciesBlock.js b/node_modules/webpack/lib/dependencies/AMDRequireDependenciesBlock.js index 92f5299ee..f86191b4a 100644 --- a/node_modules/webpack/lib/dependencies/AMDRequireDependenciesBlock.js +++ b/node_modules/webpack/lib/dependencies/AMDRequireDependenciesBlock.js @@ -1,33 +1,43 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const AsyncDependenciesBlock = require("../AsyncDependenciesBlock");
-const AMDRequireDependency = require("./AMDRequireDependency");
-
-module.exports = class AMDRequireDependenciesBlock extends AsyncDependenciesBlock {
- constructor(expr, arrayRange, functionRange, errorCallbackRange, module, loc) {
- super(null, module, loc);
- this.expr = expr;
- this.outerRange = expr.range;
- this.arrayRange = arrayRange;
- this.functionRange = functionRange;
- this.errorCallbackRange = errorCallbackRange;
- this.bindThis = true;
- if(arrayRange && functionRange && errorCallbackRange) {
- this.range = [arrayRange[0], errorCallbackRange[1]];
- } else if(arrayRange && functionRange) {
- this.range = [arrayRange[0], functionRange[1]];
- } else if(arrayRange) {
- this.range = arrayRange;
- } else if(functionRange) {
- this.range = functionRange;
- } else {
- this.range = expr.range;
- }
- const dep = new AMDRequireDependency(this);
- dep.loc = loc;
- this.addDependency(dep);
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const AsyncDependenciesBlock = require("../AsyncDependenciesBlock"); +const AMDRequireDependency = require("./AMDRequireDependency"); + +module.exports = class AMDRequireDependenciesBlock extends AsyncDependenciesBlock { + constructor( + expr, + arrayRange, + functionRange, + errorCallbackRange, + module, + loc, + request + ) { + super(null, module, loc, request); + this.expr = expr; + this.outerRange = expr.range; + this.arrayRange = arrayRange; + this.functionBindThis = false; + this.functionRange = functionRange; + this.errorCallbackBindThis = false; + this.errorCallbackRange = errorCallbackRange; + this.bindThis = true; + if (arrayRange && functionRange && errorCallbackRange) { + this.range = [arrayRange[0], errorCallbackRange[1]]; + } else if (arrayRange && functionRange) { + this.range = [arrayRange[0], functionRange[1]]; + } else if (arrayRange) { + this.range = arrayRange; + } else if (functionRange) { + this.range = functionRange; + } else { + this.range = expr.range; + } + const dep = new AMDRequireDependency(this); + dep.loc = loc; + this.addDependency(dep); + } +}; diff --git a/node_modules/webpack/lib/dependencies/AMDRequireDependenciesBlockParserPlugin.js b/node_modules/webpack/lib/dependencies/AMDRequireDependenciesBlockParserPlugin.js index 8bd7ae425..e6826722e 100644 --- a/node_modules/webpack/lib/dependencies/AMDRequireDependenciesBlockParserPlugin.js +++ b/node_modules/webpack/lib/dependencies/AMDRequireDependenciesBlockParserPlugin.js @@ -1,177 +1,272 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const AMDRequireItemDependency = require("./AMDRequireItemDependency");
-const AMDRequireArrayDependency = require("./AMDRequireArrayDependency");
-const AMDRequireContextDependency = require("./AMDRequireContextDependency");
-const AMDRequireDependenciesBlock = require("./AMDRequireDependenciesBlock");
-const UnsupportedDependency = require("./UnsupportedDependency");
-const LocalModuleDependency = require("./LocalModuleDependency");
-const ContextDependencyHelpers = require("./ContextDependencyHelpers");
-const LocalModulesHelpers = require("./LocalModulesHelpers");
-const ConstDependency = require("./ConstDependency");
-const getFunctionExpression = require("./getFunctionExpression");
-const UnsupportedFeatureWarning = require("../UnsupportedFeatureWarning");
-
-class AMDRequireDependenciesBlockParserPlugin {
- constructor(options) {
- this.options = options;
- }
-
- processFunctionArgument(parser, expression) {
- let bindThis = true;
- const fnData = getFunctionExpression(expression);
- if(fnData) {
- parser.inScope(fnData.fn.params.filter((i) => {
- return ["require", "module", "exports"].indexOf(i.name) < 0;
- }), () => {
- if(fnData.fn.body.type === "BlockStatement")
- parser.walkStatement(fnData.fn.body);
- else
- parser.walkExpression(fnData.fn.body);
- });
- parser.walkExpressions(fnData.expressions);
- if(fnData.needThis === false) {
- bindThis = false;
- }
- } else {
- parser.walkExpression(expression);
- }
- return bindThis;
- }
-
- apply(parser) {
- const options = this.options;
- parser.plugin("call require", (expr) => {
- let param;
- let dep;
- let result;
-
- const old = parser.state.current;
-
- if(expr.arguments.length >= 1) {
- param = parser.evaluateExpression(expr.arguments[0]);
- dep = new AMDRequireDependenciesBlock(
- expr,
- param.range,
- (expr.arguments.length > 1) ? expr.arguments[1].range : null,
- (expr.arguments.length > 2) ? expr.arguments[2].range : null,
- parser.state.module,
- expr.loc
- );
- parser.state.current = dep;
- }
-
- if(expr.arguments.length === 1) {
- parser.inScope([], () => {
- result = parser.applyPluginsBailResult("call require:amd:array", expr, param);
- });
- parser.state.current = old;
- if(!result) return;
- parser.state.current.addBlock(dep);
- return true;
- }
-
- if(expr.arguments.length === 2 || expr.arguments.length === 3) {
- try {
- parser.inScope([], () => {
- result = parser.applyPluginsBailResult("call require:amd:array", expr, param);
- });
- if(!result) {
- dep = new UnsupportedDependency("unsupported", expr.range);
- old.addDependency(dep);
- if(parser.state.module)
- parser.state.module.errors.push(new UnsupportedFeatureWarning(parser.state.module, "Cannot statically analyse 'require(..., ...)' in line " + expr.loc.start.line));
- dep = null;
- return true;
- }
- dep.functionBindThis = this.processFunctionArgument(parser, expr.arguments[1]);
- if(expr.arguments.length === 3) {
- dep.errorCallbackBindThis = this.processFunctionArgument(parser, expr.arguments[2]);
- }
- } finally {
- parser.state.current = old;
- if(dep)
- parser.state.current.addBlock(dep);
- }
- return true;
- }
- });
- parser.plugin("call require:amd:array", (expr, param) => {
- if(param.isArray()) {
- param.items.forEach((param) => {
- const result = parser.applyPluginsBailResult("call require:amd:item", expr, param);
- if(result === undefined) {
- parser.applyPluginsBailResult("call require:amd:context", expr, param);
- }
- });
- return true;
- } else if(param.isConstArray()) {
- const deps = [];
- param.array.forEach((request) => {
- let dep, localModule;
- if(request === "require") {
- dep = "__webpack_require__";
- } else if(["exports", "module"].indexOf(request) >= 0) {
- dep = request;
- } else if(localModule = LocalModulesHelpers.getLocalModule(parser.state, request)) { // eslint-disable-line no-cond-assign
- dep = new LocalModuleDependency(localModule);
- dep.loc = expr.loc;
- parser.state.current.addDependency(dep);
- } else {
- dep = new AMDRequireItemDependency(request);
- dep.loc = expr.loc;
- dep.optional = !!parser.scope.inTry;
- parser.state.current.addDependency(dep);
- }
- deps.push(dep);
- });
- const dep = new AMDRequireArrayDependency(deps, param.range);
- dep.loc = expr.loc;
- dep.optional = !!parser.scope.inTry;
- parser.state.current.addDependency(dep);
- return true;
- }
- });
- parser.plugin("call require:amd:item", (expr, param) => {
- if(param.isConditional()) {
- param.options.forEach((param) => {
- const result = parser.applyPluginsBailResult("call require:amd:item", expr, param);
- if(result === undefined) {
- parser.applyPluginsBailResult("call require:amd:context", expr, param);
- }
- });
- return true;
- } else if(param.isString()) {
- let dep, localModule;
- if(param.string === "require") {
- dep = new ConstDependency("__webpack_require__", param.string);
- } else if(param.string === "module") {
- dep = new ConstDependency(parser.state.module.moduleArgument || "module", param.range);
- } else if(param.string === "exports") {
- dep = new ConstDependency(parser.state.module.exportsArgument || "exports", param.range);
- } else if(localModule = LocalModulesHelpers.getLocalModule(parser.state, param.string)) { // eslint-disable-line no-cond-assign
- dep = new LocalModuleDependency(localModule, param.range);
- } else {
- dep = new AMDRequireItemDependency(param.string, param.range);
- }
- dep.loc = expr.loc;
- dep.optional = !!parser.scope.inTry;
- parser.state.current.addDependency(dep);
- return true;
- }
- });
- parser.plugin("call require:amd:context", (expr, param) => {
- const dep = ContextDependencyHelpers.create(AMDRequireContextDependency, param.range, param, expr, options);
- if(!dep) return;
- dep.loc = expr.loc;
- dep.optional = !!parser.scope.inTry;
- parser.state.current.addDependency(dep);
- return true;
- });
- }
-}
-module.exports = AMDRequireDependenciesBlockParserPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const AMDRequireItemDependency = require("./AMDRequireItemDependency"); +const AMDRequireArrayDependency = require("./AMDRequireArrayDependency"); +const AMDRequireContextDependency = require("./AMDRequireContextDependency"); +const AMDRequireDependenciesBlock = require("./AMDRequireDependenciesBlock"); +const UnsupportedDependency = require("./UnsupportedDependency"); +const LocalModuleDependency = require("./LocalModuleDependency"); +const ContextDependencyHelpers = require("./ContextDependencyHelpers"); +const LocalModulesHelpers = require("./LocalModulesHelpers"); +const ConstDependency = require("./ConstDependency"); +const getFunctionExpression = require("./getFunctionExpression"); +const UnsupportedFeatureWarning = require("../UnsupportedFeatureWarning"); + +class AMDRequireDependenciesBlockParserPlugin { + constructor(options) { + this.options = options; + } + + processFunctionArgument(parser, expression) { + let bindThis = true; + const fnData = getFunctionExpression(expression); + if (fnData) { + parser.inScope( + fnData.fn.params.filter(i => { + return !["require", "module", "exports"].includes(i.name); + }), + () => { + if (fnData.fn.body.type === "BlockStatement") { + parser.walkStatement(fnData.fn.body); + } else { + parser.walkExpression(fnData.fn.body); + } + } + ); + parser.walkExpressions(fnData.expressions); + if (fnData.needThis === false) { + bindThis = false; + } + } else { + parser.walkExpression(expression); + } + return bindThis; + } + + apply(parser) { + parser.hooks.call + .for("require") + .tap( + "AMDRequireDependenciesBlockParserPlugin", + this.processCallRequire.bind(this, parser) + ); + } + + processArray(parser, expr, param) { + if (param.isArray()) { + for (const p of param.items) { + const result = this.processItem(parser, expr, p); + if (result === undefined) { + this.processContext(parser, expr, p); + } + } + return true; + } else if (param.isConstArray()) { + const deps = []; + for (const request of param.array) { + let dep, localModule; + if (request === "require") { + dep = "__webpack_require__"; + } else if (["exports", "module"].includes(request)) { + dep = request; + } else if ( + (localModule = LocalModulesHelpers.getLocalModule( + parser.state, + request + )) + ) { + dep = new LocalModuleDependency(localModule, undefined, false); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + } else { + dep = this.newRequireItemDependency(request); + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + } + deps.push(dep); + } + const dep = this.newRequireArrayDependency(deps, param.range); + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + } + } + processItem(parser, expr, param) { + if (param.isConditional()) { + for (const p of param.options) { + const result = this.processItem(parser, expr, p); + if (result === undefined) { + this.processContext(parser, expr, p); + } + } + return true; + } else if (param.isString()) { + let dep, localModule; + if (param.string === "require") { + dep = new ConstDependency("__webpack_require__", param.string); + } else if (param.string === "module") { + dep = new ConstDependency( + parser.state.module.buildInfo.moduleArgument, + param.range + ); + } else if (param.string === "exports") { + dep = new ConstDependency( + parser.state.module.buildInfo.exportsArgument, + param.range + ); + } else if ( + (localModule = LocalModulesHelpers.getLocalModule( + parser.state, + param.string + )) + ) { + dep = new LocalModuleDependency(localModule, param.range, false); + } else { + dep = this.newRequireItemDependency(param.string, param.range); + } + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + } + } + processContext(parser, expr, param) { + const dep = ContextDependencyHelpers.create( + AMDRequireContextDependency, + param.range, + param, + expr, + this.options + ); + if (!dep) return; + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + } + + processArrayForRequestString(param) { + if (param.isArray()) { + const result = param.items.map(item => + this.processItemForRequestString(item) + ); + if (result.every(Boolean)) return result.join(" "); + } else if (param.isConstArray()) { + return param.array.join(" "); + } + } + + processItemForRequestString(param) { + if (param.isConditional()) { + const result = param.options.map(item => + this.processItemForRequestString(item) + ); + if (result.every(Boolean)) return result.join("|"); + } else if (param.isString()) { + return param.string; + } + } + + processCallRequire(parser, expr) { + let param; + let dep; + let result; + + const old = parser.state.current; + + if (expr.arguments.length >= 1) { + param = parser.evaluateExpression(expr.arguments[0]); + dep = this.newRequireDependenciesBlock( + expr, + param.range, + expr.arguments.length > 1 ? expr.arguments[1].range : null, + expr.arguments.length > 2 ? expr.arguments[2].range : null, + parser.state.module, + expr.loc, + this.processArrayForRequestString(param) + ); + parser.state.current = dep; + } + + if (expr.arguments.length === 1) { + parser.inScope([], () => { + result = this.processArray(parser, expr, param); + }); + parser.state.current = old; + if (!result) return; + parser.state.current.addBlock(dep); + return true; + } + + if (expr.arguments.length === 2 || expr.arguments.length === 3) { + try { + parser.inScope([], () => { + result = this.processArray(parser, expr, param); + }); + if (!result) { + dep = new UnsupportedDependency("unsupported", expr.range); + old.addDependency(dep); + if (parser.state.module) { + parser.state.module.errors.push( + new UnsupportedFeatureWarning( + parser.state.module, + "Cannot statically analyse 'require(…, …)' in line " + + expr.loc.start.line, + expr.loc + ) + ); + } + dep = null; + return true; + } + dep.functionBindThis = this.processFunctionArgument( + parser, + expr.arguments[1] + ); + if (expr.arguments.length === 3) { + dep.errorCallbackBindThis = this.processFunctionArgument( + parser, + expr.arguments[2] + ); + } + } finally { + parser.state.current = old; + if (dep) parser.state.current.addBlock(dep); + } + return true; + } + } + + newRequireDependenciesBlock( + expr, + arrayRange, + functionRange, + errorCallbackRange, + module, + loc, + request + ) { + return new AMDRequireDependenciesBlock( + expr, + arrayRange, + functionRange, + errorCallbackRange, + module, + loc, + request + ); + } + newRequireItemDependency(request, range) { + return new AMDRequireItemDependency(request, range); + } + newRequireArrayDependency(depsArray, range) { + return new AMDRequireArrayDependency(depsArray, range); + } +} +module.exports = AMDRequireDependenciesBlockParserPlugin; diff --git a/node_modules/webpack/lib/dependencies/AMDRequireDependency.js b/node_modules/webpack/lib/dependencies/AMDRequireDependency.js index aa5b04a32..fd514e25f 100644 --- a/node_modules/webpack/lib/dependencies/AMDRequireDependency.js +++ b/node_modules/webpack/lib/dependencies/AMDRequireDependency.js @@ -1,67 +1,135 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const NullDependency = require("./NullDependency");
-const DepBlockHelpers = require("./DepBlockHelpers");
-
-class AMDRequireDependency extends NullDependency {
- constructor(block) {
- super();
- this.block = block;
- }
-}
-
-AMDRequireDependency.Template = class AMDRequireDependencyTemplate {
- apply(dep, source, outputOptions, requestShortener) {
- const depBlock = dep.block;
- const wrapper = DepBlockHelpers.getLoadDepBlockWrapper(depBlock, outputOptions, requestShortener, "require");
-
- // has array range but no function range
- if(depBlock.arrayRange && !depBlock.functionRange) {
- const startBlock = wrapper[0] + "function() {";
- const endBlock = `;}${wrapper[1]}__webpack_require__.oe${wrapper[2]}`;
- source.replace(depBlock.outerRange[0], depBlock.arrayRange[0] - 1, startBlock);
- source.replace(depBlock.arrayRange[1], depBlock.outerRange[1] - 1, endBlock);
- return;
- }
-
- // has function range but no array range
- if(depBlock.functionRange && !depBlock.arrayRange) {
- const startBlock = wrapper[0] + "function() {(";
- const endBlock = `.call(exports, __webpack_require__, exports, module));}${wrapper[1]}__webpack_require__.oe${wrapper[2]}`;
- source.replace(depBlock.outerRange[0], depBlock.functionRange[0] - 1, startBlock);
- source.replace(depBlock.functionRange[1], depBlock.outerRange[1] - 1, endBlock);
- return;
- }
-
- // has array range, function range, and errorCallbackRange
- if(depBlock.arrayRange && depBlock.functionRange && depBlock.errorCallbackRange) {
- const startBlock = wrapper[0] + "function() { ";
- const errorRangeBlock = `}${depBlock.functionBindThis ? ".bind(this)" : ""}${wrapper[1]}`;
- const endBlock = `${depBlock.errorCallbackBindThis ? ".bind(this)" : ""}${wrapper[2]}`;
-
- source.replace(depBlock.outerRange[0], depBlock.arrayRange[0] - 1, startBlock);
- source.insert(depBlock.arrayRange[0] + 0.9, "var __WEBPACK_AMD_REQUIRE_ARRAY__ = ");
- source.replace(depBlock.arrayRange[1], depBlock.functionRange[0] - 1, "; ((");
- source.insert(depBlock.functionRange[1], ").apply(null, __WEBPACK_AMD_REQUIRE_ARRAY__));");
- source.replace(depBlock.functionRange[1], depBlock.errorCallbackRange[0] - 1, errorRangeBlock);
- source.replace(depBlock.errorCallbackRange[1], depBlock.outerRange[1] - 1, endBlock);
- return;
- }
-
- // has array range, function range, but no errorCallbackRange
- if(depBlock.arrayRange && depBlock.functionRange) {
- const startBlock = wrapper[0] + "function() { ";
- const endBlock = `}${depBlock.functionBindThis ? ".bind(this)" : ""}${wrapper[1]}__webpack_require__.oe${wrapper[2]}`;
- source.replace(depBlock.outerRange[0], depBlock.arrayRange[0] - 1, startBlock);
- source.insert(depBlock.arrayRange[0] + 0.9, "var __WEBPACK_AMD_REQUIRE_ARRAY__ = ");
- source.replace(depBlock.arrayRange[1], depBlock.functionRange[0] - 1, "; ((");
- source.insert(depBlock.functionRange[1], ").apply(null, __WEBPACK_AMD_REQUIRE_ARRAY__));");
- source.replace(depBlock.functionRange[1], depBlock.outerRange[1] - 1, endBlock);
- }
- }
-};
-
-module.exports = AMDRequireDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const NullDependency = require("./NullDependency"); + +class AMDRequireDependency extends NullDependency { + constructor(block) { + super(); + this.block = block; + } +} + +AMDRequireDependency.Template = class AMDRequireDependencyTemplate { + apply(dep, source, runtime) { + const depBlock = dep.block; + const promise = runtime.blockPromise({ + block: depBlock, + message: "AMD require" + }); + + // has array range but no function range + if (depBlock.arrayRange && !depBlock.functionRange) { + const startBlock = `${promise}.then(function() {`; + const endBlock = `;}).catch(${runtime.onError()})`; + source.replace( + depBlock.outerRange[0], + depBlock.arrayRange[0] - 1, + startBlock + ); + source.replace( + depBlock.arrayRange[1], + depBlock.outerRange[1] - 1, + endBlock + ); + return; + } + + // has function range but no array range + if (depBlock.functionRange && !depBlock.arrayRange) { + const startBlock = `${promise}.then((`; + const endBlock = `).bind(exports, __webpack_require__, exports, module)).catch(${runtime.onError()})`; + source.replace( + depBlock.outerRange[0], + depBlock.functionRange[0] - 1, + startBlock + ); + source.replace( + depBlock.functionRange[1], + depBlock.outerRange[1] - 1, + endBlock + ); + return; + } + + // has array range, function range, and errorCallbackRange + if ( + depBlock.arrayRange && + depBlock.functionRange && + depBlock.errorCallbackRange + ) { + const startBlock = `${promise}.then(function() { `; + const errorRangeBlock = `}${ + depBlock.functionBindThis ? ".bind(this)" : "" + }).catch(`; + const endBlock = `${ + depBlock.errorCallbackBindThis ? ".bind(this)" : "" + })`; + + source.replace( + depBlock.outerRange[0], + depBlock.arrayRange[0] - 1, + startBlock + ); + source.insert( + depBlock.arrayRange[0] + 0.9, + "var __WEBPACK_AMD_REQUIRE_ARRAY__ = " + ); + source.replace( + depBlock.arrayRange[1], + depBlock.functionRange[0] - 1, + "; (" + ); + source.insert( + depBlock.functionRange[1], + ").apply(null, __WEBPACK_AMD_REQUIRE_ARRAY__);" + ); + source.replace( + depBlock.functionRange[1], + depBlock.errorCallbackRange[0] - 1, + errorRangeBlock + ); + source.replace( + depBlock.errorCallbackRange[1], + depBlock.outerRange[1] - 1, + endBlock + ); + return; + } + + // has array range, function range, but no errorCallbackRange + if (depBlock.arrayRange && depBlock.functionRange) { + const startBlock = `${promise}.then(function() { `; + const endBlock = `}${ + depBlock.functionBindThis ? ".bind(this)" : "" + }).catch(${runtime.onError()})`; + source.replace( + depBlock.outerRange[0], + depBlock.arrayRange[0] - 1, + startBlock + ); + source.insert( + depBlock.arrayRange[0] + 0.9, + "var __WEBPACK_AMD_REQUIRE_ARRAY__ = " + ); + source.replace( + depBlock.arrayRange[1], + depBlock.functionRange[0] - 1, + "; (" + ); + source.insert( + depBlock.functionRange[1], + ").apply(null, __WEBPACK_AMD_REQUIRE_ARRAY__);" + ); + source.replace( + depBlock.functionRange[1], + depBlock.outerRange[1] - 1, + endBlock + ); + } + } +}; + +module.exports = AMDRequireDependency; diff --git a/node_modules/webpack/lib/dependencies/AMDRequireItemDependency.js b/node_modules/webpack/lib/dependencies/AMDRequireItemDependency.js index 60401d533..d033a90d8 100644 --- a/node_modules/webpack/lib/dependencies/AMDRequireItemDependency.js +++ b/node_modules/webpack/lib/dependencies/AMDRequireItemDependency.js @@ -1,22 +1,22 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const ModuleDependency = require("./ModuleDependency");
-const ModuleDependencyTemplateAsRequireId = require("./ModuleDependencyTemplateAsRequireId");
-
-class AMDRequireItemDependency extends ModuleDependency {
- constructor(request, range) {
- super(request);
- this.range = range;
- }
-
- get type() {
- return "amd require";
- }
-}
-
-AMDRequireItemDependency.Template = ModuleDependencyTemplateAsRequireId;
-
-module.exports = AMDRequireItemDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const ModuleDependency = require("./ModuleDependency"); +const ModuleDependencyTemplateAsRequireId = require("./ModuleDependencyTemplateAsRequireId"); + +class AMDRequireItemDependency extends ModuleDependency { + constructor(request, range) { + super(request); + this.range = range; + } + + get type() { + return "amd require"; + } +} + +AMDRequireItemDependency.Template = ModuleDependencyTemplateAsRequireId; + +module.exports = AMDRequireItemDependency; diff --git a/node_modules/webpack/lib/dependencies/CommonJsPlugin.js b/node_modules/webpack/lib/dependencies/CommonJsPlugin.js index 218cddb3d..6d441a872 100644 --- a/node_modules/webpack/lib/dependencies/CommonJsPlugin.js +++ b/node_modules/webpack/lib/dependencies/CommonJsPlugin.js @@ -1,89 +1,158 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const ConstDependency = require("./ConstDependency");
-const CommonJsRequireDependency = require("./CommonJsRequireDependency");
-const CommonJsRequireContextDependency = require("./CommonJsRequireContextDependency");
-const RequireResolveDependency = require("./RequireResolveDependency");
-const RequireResolveContextDependency = require("./RequireResolveContextDependency");
-const RequireResolveHeaderDependency = require("./RequireResolveHeaderDependency");
-const RequireHeaderDependency = require("./RequireHeaderDependency");
-
-const NullFactory = require("../NullFactory");
-
-const RequireResolveDependencyParserPlugin = require("./RequireResolveDependencyParserPlugin");
-const CommonJsRequireDependencyParserPlugin = require("./CommonJsRequireDependencyParserPlugin");
-
-const ParserHelpers = require("../ParserHelpers");
-
-class CommonJsPlugin {
- constructor(options) {
- this.options = options;
- }
-
- apply(compiler) {
- const options = this.options;
- compiler.plugin("compilation", (compilation, params) => {
- const normalModuleFactory = params.normalModuleFactory;
- const contextModuleFactory = params.contextModuleFactory;
-
- compilation.dependencyFactories.set(CommonJsRequireDependency, normalModuleFactory);
- compilation.dependencyTemplates.set(CommonJsRequireDependency, new CommonJsRequireDependency.Template());
-
- compilation.dependencyFactories.set(CommonJsRequireContextDependency, contextModuleFactory);
- compilation.dependencyTemplates.set(CommonJsRequireContextDependency, new CommonJsRequireContextDependency.Template());
-
- compilation.dependencyFactories.set(RequireResolveDependency, normalModuleFactory);
- compilation.dependencyTemplates.set(RequireResolveDependency, new RequireResolveDependency.Template());
-
- compilation.dependencyFactories.set(RequireResolveContextDependency, contextModuleFactory);
- compilation.dependencyTemplates.set(RequireResolveContextDependency, new RequireResolveContextDependency.Template());
-
- compilation.dependencyFactories.set(RequireResolveHeaderDependency, new NullFactory());
- compilation.dependencyTemplates.set(RequireResolveHeaderDependency, new RequireResolveHeaderDependency.Template());
-
- compilation.dependencyFactories.set(RequireHeaderDependency, new NullFactory());
- compilation.dependencyTemplates.set(RequireHeaderDependency, new RequireHeaderDependency.Template());
-
- params.normalModuleFactory.plugin("parser", (parser, parserOptions) => {
-
- if(typeof parserOptions.commonjs !== "undefined" && !parserOptions.commonjs)
- return;
-
- const requireExpressions = ["require", "require.resolve", "require.resolveWeak"];
- for(let expression of requireExpressions) {
- parser.plugin(`typeof ${expression}`, ParserHelpers.toConstantDependency(JSON.stringify("function")));
- parser.plugin(`evaluate typeof ${expression}`, ParserHelpers.evaluateToString("function"));
- parser.plugin(`evaluate Identifier ${expression}`, ParserHelpers.evaluateToIdentifier(expression, true));
- }
-
- parser.plugin("evaluate typeof module", ParserHelpers.evaluateToString("object"));
- parser.plugin("assign require", (expr) => {
- // to not leak to global "require", we need to define a local require here.
- const dep = new ConstDependency("var require;", 0);
- dep.loc = expr.loc;
- parser.state.current.addDependency(dep);
- parser.scope.definitions.push("require");
- return true;
- });
- parser.plugin("can-rename require", () => true);
- parser.plugin("rename require", (expr) => {
- // define the require variable. It's still undefined, but not "not defined".
- const dep = new ConstDependency("var require;", 0);
- dep.loc = expr.loc;
- parser.state.current.addDependency(dep);
- return false;
- });
- parser.plugin("typeof module", () => true);
- parser.plugin("evaluate typeof exports", ParserHelpers.evaluateToString("object"));
- parser.apply(
- new CommonJsRequireDependencyParserPlugin(options),
- new RequireResolveDependencyParserPlugin(options)
- );
- });
- });
- }
-}
-module.exports = CommonJsPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const ConstDependency = require("./ConstDependency"); +const CommonJsRequireDependency = require("./CommonJsRequireDependency"); +const CommonJsRequireContextDependency = require("./CommonJsRequireContextDependency"); +const RequireResolveDependency = require("./RequireResolveDependency"); +const RequireResolveContextDependency = require("./RequireResolveContextDependency"); +const RequireResolveHeaderDependency = require("./RequireResolveHeaderDependency"); +const RequireHeaderDependency = require("./RequireHeaderDependency"); + +const NullFactory = require("../NullFactory"); + +const RequireResolveDependencyParserPlugin = require("./RequireResolveDependencyParserPlugin"); +const CommonJsRequireDependencyParserPlugin = require("./CommonJsRequireDependencyParserPlugin"); + +const ParserHelpers = require("../ParserHelpers"); + +class CommonJsPlugin { + constructor(options) { + this.options = options; + } + + apply(compiler) { + const options = this.options; + compiler.hooks.compilation.tap( + "CommonJsPlugin", + (compilation, { contextModuleFactory, normalModuleFactory }) => { + compilation.dependencyFactories.set( + CommonJsRequireDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + CommonJsRequireDependency, + new CommonJsRequireDependency.Template() + ); + + compilation.dependencyFactories.set( + CommonJsRequireContextDependency, + contextModuleFactory + ); + compilation.dependencyTemplates.set( + CommonJsRequireContextDependency, + new CommonJsRequireContextDependency.Template() + ); + + compilation.dependencyFactories.set( + RequireResolveDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + RequireResolveDependency, + new RequireResolveDependency.Template() + ); + + compilation.dependencyFactories.set( + RequireResolveContextDependency, + contextModuleFactory + ); + compilation.dependencyTemplates.set( + RequireResolveContextDependency, + new RequireResolveContextDependency.Template() + ); + + compilation.dependencyFactories.set( + RequireResolveHeaderDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + RequireResolveHeaderDependency, + new RequireResolveHeaderDependency.Template() + ); + + compilation.dependencyFactories.set( + RequireHeaderDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + RequireHeaderDependency, + new RequireHeaderDependency.Template() + ); + + const handler = (parser, parserOptions) => { + if (parserOptions.commonjs !== undefined && !parserOptions.commonjs) + return; + + const requireExpressions = [ + "require", + "require.resolve", + "require.resolveWeak" + ]; + for (let expression of requireExpressions) { + parser.hooks.typeof + .for(expression) + .tap( + "CommonJsPlugin", + ParserHelpers.toConstantDependency( + parser, + JSON.stringify("function") + ) + ); + parser.hooks.evaluateTypeof + .for(expression) + .tap( + "CommonJsPlugin", + ParserHelpers.evaluateToString("function") + ); + parser.hooks.evaluateIdentifier + .for(expression) + .tap( + "CommonJsPlugin", + ParserHelpers.evaluateToIdentifier(expression, true) + ); + } + + parser.hooks.evaluateTypeof + .for("module") + .tap("CommonJsPlugin", ParserHelpers.evaluateToString("object")); + parser.hooks.assign.for("require").tap("CommonJsPlugin", expr => { + // to not leak to global "require", we need to define a local require here. + const dep = new ConstDependency("var require;", 0); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + parser.scope.definitions.add("require"); + return true; + }); + parser.hooks.canRename + .for("require") + .tap("CommonJsPlugin", () => true); + parser.hooks.rename.for("require").tap("CommonJsPlugin", expr => { + // define the require variable. It's still undefined, but not "not defined". + const dep = new ConstDependency("var require;", 0); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + return false; + }); + parser.hooks.typeof.for("module").tap("CommonJsPlugin", () => true); + parser.hooks.evaluateTypeof + .for("exports") + .tap("CommonJsPlugin", ParserHelpers.evaluateToString("object")); + + new CommonJsRequireDependencyParserPlugin(options).apply(parser); + new RequireResolveDependencyParserPlugin(options).apply(parser); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("CommonJsPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("CommonJsPlugin", handler); + } + ); + } +} +module.exports = CommonJsPlugin; diff --git a/node_modules/webpack/lib/dependencies/CommonJsRequireContextDependency.js b/node_modules/webpack/lib/dependencies/CommonJsRequireContextDependency.js index 6e8e33f08..723a849e7 100644 --- a/node_modules/webpack/lib/dependencies/CommonJsRequireContextDependency.js +++ b/node_modules/webpack/lib/dependencies/CommonJsRequireContextDependency.js @@ -1,24 +1,23 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const ContextDependency = require("./ContextDependency");
-const ContextDependencyTemplateAsRequireCall = require("./ContextDependencyTemplateAsRequireCall");
-
-class CommonJsRequireContextDependency extends ContextDependency {
- constructor(request, recursive, regExp, range, valueRange) {
- super(request, recursive, regExp);
- this.range = range;
- this.valueRange = valueRange;
- }
-
- get type() {
- return "cjs require context";
- }
-
-}
-
-CommonJsRequireContextDependency.Template = ContextDependencyTemplateAsRequireCall;
-
-module.exports = CommonJsRequireContextDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const ContextDependency = require("./ContextDependency"); +const ContextDependencyTemplateAsRequireCall = require("./ContextDependencyTemplateAsRequireCall"); + +class CommonJsRequireContextDependency extends ContextDependency { + constructor(options, range, valueRange) { + super(options); + this.range = range; + this.valueRange = valueRange; + } + + get type() { + return "cjs require context"; + } +} + +CommonJsRequireContextDependency.Template = ContextDependencyTemplateAsRequireCall; + +module.exports = CommonJsRequireContextDependency; diff --git a/node_modules/webpack/lib/dependencies/CommonJsRequireDependency.js b/node_modules/webpack/lib/dependencies/CommonJsRequireDependency.js index bd9e68e46..29a30f343 100644 --- a/node_modules/webpack/lib/dependencies/CommonJsRequireDependency.js +++ b/node_modules/webpack/lib/dependencies/CommonJsRequireDependency.js @@ -1,22 +1,22 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const ModuleDependency = require("./ModuleDependency");
-const ModuleDependencyTemplateAsId = require("./ModuleDependencyTemplateAsId");
-
-class CommonJsRequireDependency extends ModuleDependency {
- constructor(request, range) {
- super(request);
- this.range = range;
- }
-
- get type() {
- return "cjs require";
- }
-}
-
-CommonJsRequireDependency.Template = ModuleDependencyTemplateAsId;
-
-module.exports = CommonJsRequireDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const ModuleDependency = require("./ModuleDependency"); +const ModuleDependencyTemplateAsId = require("./ModuleDependencyTemplateAsId"); + +class CommonJsRequireDependency extends ModuleDependency { + constructor(request, range) { + super(request); + this.range = range; + } + + get type() { + return "cjs require"; + } +} + +CommonJsRequireDependency.Template = ModuleDependencyTemplateAsId; + +module.exports = CommonJsRequireDependency; diff --git a/node_modules/webpack/lib/dependencies/CommonJsRequireDependencyParserPlugin.js b/node_modules/webpack/lib/dependencies/CommonJsRequireDependencyParserPlugin.js index 2e2fee613..875657348 100644 --- a/node_modules/webpack/lib/dependencies/CommonJsRequireDependencyParserPlugin.js +++ b/node_modules/webpack/lib/dependencies/CommonJsRequireDependencyParserPlugin.js @@ -1,89 +1,136 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const CommonJsRequireDependency = require("./CommonJsRequireDependency");
-const CommonJsRequireContextDependency = require("./CommonJsRequireContextDependency");
-const RequireHeaderDependency = require("./RequireHeaderDependency");
-const LocalModuleDependency = require("./LocalModuleDependency");
-const ContextDependencyHelpers = require("./ContextDependencyHelpers");
-const LocalModulesHelpers = require("./LocalModulesHelpers");
-const ParserHelpers = require("../ParserHelpers");
-
-class CommonJsRequireDependencyParserPlugin {
- constructor(options) {
- this.options = options;
- }
-
- apply(parser) {
- const options = this.options;
- parser.plugin("expression require.cache", ParserHelpers.toConstantDependency("__webpack_require__.c"));
- parser.plugin("expression require", (expr) => {
- const dep = new CommonJsRequireContextDependency(options.unknownContextRequest, options.unknownContextRecursive, options.unknownContextRegExp, expr.range);
- dep.critical = options.unknownContextCritical && "require function is used in a way in which dependencies cannot be statically extracted";
- dep.loc = expr.loc;
- dep.optional = !!parser.scope.inTry;
- parser.state.current.addDependency(dep);
- return true;
- });
- parser.plugin("call require", (expr) => {
- if(expr.arguments.length !== 1) return;
- let localModule;
- const param = parser.evaluateExpression(expr.arguments[0]);
- if(param.isConditional()) {
- let isExpression = false;
- const prevLength = parser.state.current.dependencies.length;
- const dep = new RequireHeaderDependency(expr.callee.range);
- dep.loc = expr.loc;
- parser.state.current.addDependency(dep);
- param.options.forEach(function(param) {
- const result = parser.applyPluginsBailResult("call require:commonjs:item", expr, param);
- if(result === undefined) {
- isExpression = true;
- }
- });
- if(isExpression) {
- parser.state.current.dependencies.length = prevLength;
- } else {
- return true;
- }
- }
- if(param.isString() && (localModule = LocalModulesHelpers.getLocalModule(parser.state, param.string))) {
- const dep = new LocalModuleDependency(localModule, expr.range);
- dep.loc = expr.loc;
- parser.state.current.addDependency(dep);
- return true;
- } else {
- const result = parser.applyPluginsBailResult("call require:commonjs:item", expr, param);
- if(result === undefined) {
- parser.applyPluginsBailResult("call require:commonjs:context", expr, param);
- } else {
- const dep = new RequireHeaderDependency(expr.callee.range);
- dep.loc = expr.loc;
- parser.state.current.addDependency(dep);
- }
- return true;
- }
- });
- parser.plugin("call require:commonjs:item", (expr, param) => {
- if(param.isString()) {
- const dep = new CommonJsRequireDependency(param.string, param.range);
- dep.loc = expr.loc;
- dep.optional = !!parser.scope.inTry;
- parser.state.current.addDependency(dep);
- return true;
- }
- });
- parser.plugin("call require:commonjs:context", (expr, param) => {
- const dep = ContextDependencyHelpers.create(CommonJsRequireContextDependency, expr.range, param, expr, options);
- if(!dep) return;
- dep.loc = expr.loc;
- dep.optional = !!parser.scope.inTry;
- parser.state.current.addDependency(dep);
- return true;
- });
- }
-}
-module.exports = CommonJsRequireDependencyParserPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const CommonJsRequireDependency = require("./CommonJsRequireDependency"); +const CommonJsRequireContextDependency = require("./CommonJsRequireContextDependency"); +const RequireHeaderDependency = require("./RequireHeaderDependency"); +const LocalModuleDependency = require("./LocalModuleDependency"); +const ContextDependencyHelpers = require("./ContextDependencyHelpers"); +const LocalModulesHelpers = require("./LocalModulesHelpers"); +const ParserHelpers = require("../ParserHelpers"); + +class CommonJsRequireDependencyParserPlugin { + constructor(options) { + this.options = options; + } + + apply(parser) { + const options = this.options; + + const processItem = (expr, param) => { + if (param.isString()) { + const dep = new CommonJsRequireDependency(param.string, param.range); + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + } + }; + const processContext = (expr, param) => { + const dep = ContextDependencyHelpers.create( + CommonJsRequireContextDependency, + expr.range, + param, + expr, + options + ); + if (!dep) return; + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + }; + + parser.hooks.expression + .for("require.cache") + .tap( + "CommonJsRequireDependencyParserPlugin", + ParserHelpers.toConstantDependencyWithWebpackRequire( + parser, + "__webpack_require__.c" + ) + ); + parser.hooks.expression + .for("require") + .tap("CommonJsRequireDependencyParserPlugin", expr => { + const dep = new CommonJsRequireContextDependency( + { + request: options.unknownContextRequest, + recursive: options.unknownContextRecursive, + regExp: options.unknownContextRegExp, + mode: "sync" + }, + expr.range + ); + dep.critical = + options.unknownContextCritical && + "require function is used in a way in which dependencies cannot be statically extracted"; + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + }); + + const createHandler = callNew => expr => { + if (expr.arguments.length !== 1) return; + let localModule; + const param = parser.evaluateExpression(expr.arguments[0]); + if (param.isConditional()) { + let isExpression = false; + const prevLength = parser.state.current.dependencies.length; + const dep = new RequireHeaderDependency(expr.callee.range); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + for (const p of param.options) { + const result = processItem(expr, p); + if (result === undefined) { + isExpression = true; + } + } + if (isExpression) { + parser.state.current.dependencies.length = prevLength; + } else { + return true; + } + } + if ( + param.isString() && + (localModule = LocalModulesHelpers.getLocalModule( + parser.state, + param.string + )) + ) { + const dep = new LocalModuleDependency(localModule, expr.range, callNew); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + return true; + } else { + const result = processItem(expr, param); + if (result === undefined) { + processContext(expr, param); + } else { + const dep = new RequireHeaderDependency(expr.callee.range); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + } + return true; + } + }; + parser.hooks.call + .for("require") + .tap("CommonJsRequireDependencyParserPlugin", createHandler(false)); + parser.hooks.new + .for("require") + .tap("CommonJsRequireDependencyParserPlugin", createHandler(true)); + parser.hooks.call + .for("module.require") + .tap("CommonJsRequireDependencyParserPlugin", createHandler(false)); + parser.hooks.new + .for("module.require") + .tap("CommonJsRequireDependencyParserPlugin", createHandler(true)); + } +} +module.exports = CommonJsRequireDependencyParserPlugin; diff --git a/node_modules/webpack/lib/dependencies/ConstDependency.js b/node_modules/webpack/lib/dependencies/ConstDependency.js index 2bf2008e5..22edb8e23 100644 --- a/node_modules/webpack/lib/dependencies/ConstDependency.js +++ b/node_modules/webpack/lib/dependencies/ConstDependency.js @@ -1,32 +1,33 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const NullDependency = require("./NullDependency");
-
-class ConstDependency extends NullDependency {
- constructor(expression, range) {
- super();
- this.expression = expression;
- this.range = range;
- }
-
- updateHash(hash) {
- hash.update(this.range + "");
- hash.update(this.expression + "");
- }
-}
-
-ConstDependency.Template = class ConstDependencyTemplate {
- apply(dep, source) {
- if(typeof dep.range === "number") {
- source.insert(dep.range, dep.expression);
- return;
- }
-
- source.replace(dep.range[0], dep.range[1] - 1, dep.expression);
- }
-};
-
-module.exports = ConstDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const NullDependency = require("./NullDependency"); + +class ConstDependency extends NullDependency { + constructor(expression, range, requireWebpackRequire) { + super(); + this.expression = expression; + this.range = range; + this.requireWebpackRequire = requireWebpackRequire; + } + + updateHash(hash) { + hash.update(this.range + ""); + hash.update(this.expression + ""); + } +} + +ConstDependency.Template = class ConstDependencyTemplate { + apply(dep, source) { + if (typeof dep.range === "number") { + source.insert(dep.range, dep.expression); + return; + } + + source.replace(dep.range[0], dep.range[1] - 1, dep.expression); + } +}; + +module.exports = ConstDependency; diff --git a/node_modules/webpack/lib/dependencies/ContextDependency.js b/node_modules/webpack/lib/dependencies/ContextDependency.js index 55bc9823c..10c2fea99 100644 --- a/node_modules/webpack/lib/dependencies/ContextDependency.js +++ b/node_modules/webpack/lib/dependencies/ContextDependency.js @@ -1,49 +1,68 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const Dependency = require("../Dependency");
-const CriticalDependencyWarning = require("./CriticalDependencyWarning");
-
-class ContextDependency extends Dependency {
- constructor(request, recursive, regExp) {
- super();
- this.request = request;
- this.userRequest = request;
- this.recursive = recursive;
- this.regExp = regExp;
- this.async = false;
-
- this.hadGlobalOrStickyRegExp = false;
- if(this.regExp.global || this.regExp.sticky) {
- this.regExp = null;
- this.hadGlobalOrStickyRegExp = true;
- }
-
- }
-
- isEqualResource(other) {
- if(!(other instanceof ContextDependency))
- return false;
-
- return this.request === other.request &&
- this.recursive === other.recursive &&
- this.regExp === other.regExp &&
- this.async === other.async;
- }
-
- getWarnings() {
- let warnings = super.getWarnings() || [];
- if(this.critical) {
- warnings.push(new CriticalDependencyWarning(this.critical));
- }
- if(this.hadGlobalOrStickyRegExp) {
- warnings.push(new CriticalDependencyWarning("Contexts can't use RegExps with the 'g' or 'y' flags."));
- }
- return warnings;
- }
-
-}
-
-module.exports = ContextDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const Dependency = require("../Dependency"); +const CriticalDependencyWarning = require("./CriticalDependencyWarning"); + +const regExpToString = r => (r ? r + "" : ""); + +class ContextDependency extends Dependency { + // options: { request, recursive, regExp, include, exclude, mode, chunkName, groupOptions } + constructor(options) { + super(); + this.options = options; + this.userRequest = this.options.request; + /** @type {false | string} */ + this.critical = false; + this.hadGlobalOrStickyRegExp = false; + if (this.options.regExp.global || this.options.regExp.sticky) { + this.options.regExp = null; + this.hadGlobalOrStickyRegExp = true; + } + } + + getResourceIdentifier() { + return ( + `context${this.options.request} ${this.options.recursive} ` + + `${regExpToString(this.options.regExp)} ${regExpToString( + this.options.include + )} ${regExpToString(this.options.exclude)} ` + + `${this.options.mode} ${this.options.chunkName} ` + + `${JSON.stringify(this.options.groupOptions)}` + ); + } + + getWarnings() { + let warnings = super.getWarnings() || []; + if (this.critical) { + warnings.push(new CriticalDependencyWarning(this.critical)); + } + if (this.hadGlobalOrStickyRegExp) { + warnings.push( + new CriticalDependencyWarning( + "Contexts can't use RegExps with the 'g' or 'y' flags." + ) + ); + } + return warnings; + } +} + +// TODO remove in webpack 5 +Object.defineProperty(ContextDependency.prototype, "async", { + configurable: false, + get() { + throw new Error( + "ContextDependency.async was removed. Use ContextDependency.options.mode instead." + ); + }, + set() { + throw new Error( + "ContextDependency.async was removed. Pass options.mode to constructor instead" + ); + } +}); + +module.exports = ContextDependency; diff --git a/node_modules/webpack/lib/dependencies/ContextDependencyHelpers.js b/node_modules/webpack/lib/dependencies/ContextDependencyHelpers.js index 412cee701..2dabc3345 100644 --- a/node_modules/webpack/lib/dependencies/ContextDependencyHelpers.js +++ b/node_modules/webpack/lib/dependencies/ContextDependencyHelpers.js @@ -1,71 +1,177 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const ContextDependencyHelpers = exports;
-
-/**
- * Escapes regular expression metacharacters
- * @param {string} str String to quote
- * @return {string} Escaped string
- */
-function quotemeta(str) {
- return str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&");
-}
-
-ContextDependencyHelpers.create = function(Dep, range, param, expr, options, chunkName) {
- let dep;
- let prefix;
- let postfix;
- let prefixRange;
- let valueRange;
- let idx;
- let context;
- let regExp;
- if(param.isTemplateString()) {
- prefix = param.quasis[0].string;
- postfix = param.quasis.length > 1 ? param.quasis[param.quasis.length - 1].string : "";
- prefixRange = [param.quasis[0].range[0], param.quasis[0].range[1]];
- valueRange = param.range;
- idx = prefix.lastIndexOf("/");
- context = ".";
- if(idx >= 0) {
- context = prefix.substr(0, idx);
- prefix = `.${prefix.substr(idx)}`;
- }
- // If there are more than two quasis, maybe the generated RegExp can be more precise?
- regExp = new RegExp(`^${quotemeta(prefix)}${options.wrappedContextRegExp.source}${quotemeta(postfix)}$`);
- dep = new Dep(context, options.wrappedContextRecursive, regExp, range, valueRange, chunkName);
- dep.loc = expr.loc;
- dep.replaces = [{
- range: prefixRange,
- value: prefix
- }];
- dep.critical = options.wrappedContextCritical && "a part of the request of a dependency is an expression";
- return dep;
- } else if(param.isWrapped() && (param.prefix && param.prefix.isString() || param.postfix && param.postfix.isString())) {
- prefix = param.prefix && param.prefix.isString() ? param.prefix.string : "";
- postfix = param.postfix && param.postfix.isString() ? param.postfix.string : "";
- prefixRange = param.prefix && param.prefix.isString() ? param.prefix.range : null;
- valueRange = [prefixRange ? prefixRange[1] : param.range[0], param.range[1]];
- idx = prefix.lastIndexOf("/");
- context = ".";
- if(idx >= 0) {
- context = prefix.substr(0, idx);
- prefix = `.${prefix.substr(idx)}`;
- }
- regExp = new RegExp(`^${quotemeta(prefix)}${options.wrappedContextRegExp.source}${quotemeta(postfix)}$`);
- dep = new Dep(context, options.wrappedContextRecursive, regExp, range, valueRange, chunkName);
- dep.loc = expr.loc;
- dep.prepend = param.prefix && param.prefix.isString() ? prefix : null;
- dep.critical = options.wrappedContextCritical && "a part of the request of a dependency is an expression";
- return dep;
- } else {
- dep = new Dep(options.exprContextRequest, options.exprContextRecursive, options.exprContextRegExp, range, param.range, chunkName);
- dep.loc = expr.loc;
- dep.critical = options.exprContextCritical && "the request of a dependency is an expression";
- return dep;
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const ContextDependencyHelpers = exports; + +/** + * Escapes regular expression metacharacters + * @param {string} str String to quote + * @returns {string} Escaped string + */ +const quotemeta = str => { + return str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&"); +}; + +const splitContextFromPrefix = prefix => { + const idx = prefix.lastIndexOf("/"); + let context = "."; + if (idx >= 0) { + context = prefix.substr(0, idx); + prefix = `.${prefix.substr(idx)}`; + } + return { + context, + prefix + }; +}; + +const splitQueryFromPostfix = postfix => { + const idx = postfix.indexOf("?"); + let query = ""; + if (idx >= 0) { + query = postfix.substr(idx); + postfix = postfix.substr(0, idx); + } + return { + postfix, + query + }; +}; + +ContextDependencyHelpers.create = ( + Dep, + range, + param, + expr, + options, + contextOptions +) => { + if (param.isTemplateString()) { + let prefixRaw = param.quasis[0].string; + let postfixRaw = + param.quasis.length > 1 + ? param.quasis[param.quasis.length - 1].string + : ""; + const prefixRange = [param.quasis[0].range[0], param.quasis[0].range[1]]; + const postfixRange = + param.quasis.length > 1 + ? param.quasis[param.quasis.length - 1].range + : ""; + const valueRange = param.range; + const { context, prefix } = splitContextFromPrefix(prefixRaw); + const { postfix, query } = splitQueryFromPostfix(postfixRaw); + // If there are more than two quasis, maybe the generated RegExp can be more precise? + const regExp = new RegExp( + `^${quotemeta(prefix)}${options.wrappedContextRegExp.source}${quotemeta( + postfix + )}$` + ); + const dep = new Dep( + Object.assign( + { + request: context + query, + recursive: options.wrappedContextRecursive, + regExp, + mode: "sync" + }, + contextOptions + ), + range, + valueRange + ); + dep.loc = expr.loc; + const replaces = []; + if (prefixRange && prefix !== prefixRaw) { + replaces.push({ + range: prefixRange, + value: prefix + }); + } + if (postfixRange && postfix !== postfixRaw) { + replaces.push({ + range: postfixRange, + value: postfix + }); + } + dep.replaces = replaces; + dep.critical = + options.wrappedContextCritical && + "a part of the request of a dependency is an expression"; + return dep; + } else if ( + param.isWrapped() && + ((param.prefix && param.prefix.isString()) || + (param.postfix && param.postfix.isString())) + ) { + let prefixRaw = + param.prefix && param.prefix.isString() ? param.prefix.string : ""; + let postfixRaw = + param.postfix && param.postfix.isString() ? param.postfix.string : ""; + const prefixRange = + param.prefix && param.prefix.isString() ? param.prefix.range : null; + const postfixRange = + param.postfix && param.postfix.isString() ? param.postfix.range : null; + const valueRange = param.range; + const { context, prefix } = splitContextFromPrefix(prefixRaw); + const { postfix, query } = splitQueryFromPostfix(postfixRaw); + const regExp = new RegExp( + `^${quotemeta(prefix)}${options.wrappedContextRegExp.source}${quotemeta( + postfix + )}$` + ); + const dep = new Dep( + Object.assign( + { + request: context + query, + recursive: options.wrappedContextRecursive, + regExp, + mode: "sync" + }, + contextOptions + ), + range, + valueRange + ); + dep.loc = expr.loc; + const replaces = []; + if (prefixRange && prefix !== prefixRaw) { + replaces.push({ + range: prefixRange, + value: JSON.stringify(prefix) + }); + } + if (postfixRange && postfix !== postfixRaw) { + replaces.push({ + range: postfixRange, + value: JSON.stringify(postfix) + }); + } + dep.replaces = replaces; + dep.critical = + options.wrappedContextCritical && + "a part of the request of a dependency is an expression"; + return dep; + } else { + const dep = new Dep( + Object.assign( + { + request: options.exprContextRequest, + recursive: options.exprContextRecursive, + regExp: options.exprContextRegExp, + mode: "sync" + }, + contextOptions + ), + range, + param.range + ); + dep.loc = expr.loc; + dep.critical = + options.exprContextCritical && + "the request of a dependency is an expression"; + return dep; + } +}; diff --git a/node_modules/webpack/lib/dependencies/ContextDependencyTemplateAsId.js b/node_modules/webpack/lib/dependencies/ContextDependencyTemplateAsId.js index f88f6c85c..1ee83ff99 100644 --- a/node_modules/webpack/lib/dependencies/ContextDependencyTemplateAsId.js +++ b/node_modules/webpack/lib/dependencies/ContextDependencyTemplateAsId.js @@ -1,32 +1,43 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-class ContextDependencyTemplateAsId {
-
- apply(dep, source, outputOptions, requestShortener) {
- const comment = outputOptions.pathinfo ?
- "/*! " + requestShortener.shorten(dep.request) + " */ " : "";
-
- if(dep.module && dep.module.dependencies && dep.module.dependencies.length > 0) {
- if(dep.valueRange) {
- if(Array.isArray(dep.replaces)) {
- for(let i = 0; i < dep.replaces.length; i++) {
- const rep = dep.replaces[i];
- source.replace(rep.range[0], rep.range[1] - 1, rep.value);
- }
- }
- source.replace(dep.valueRange[1], dep.range[1] - 1, ")");
- source.replace(dep.range[0], dep.valueRange[0] - 1, "__webpack_require__(" + comment + JSON.stringify(dep.module.id) + ").resolve(" + (typeof dep.prepend === "string" ? JSON.stringify(dep.prepend) : "") + "");
- } else {
- source.replace(dep.range[0], dep.range[1] - 1, "__webpack_require__(" + comment + JSON.stringify(dep.module.id) + ").resolve");
- }
- } else {
- const content = require("./WebpackMissingModule").module(dep.request);
- source.replace(dep.range[0], dep.range[1] - 1, content);
- }
- }
-}
-module.exports = ContextDependencyTemplateAsId;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +class ContextDependencyTemplateAsId { + apply(dep, source, runtime) { + const moduleExports = runtime.moduleExports({ + module: dep.module, + request: dep.request + }); + + if (dep.module) { + if (dep.valueRange) { + if (Array.isArray(dep.replaces)) { + for (let i = 0; i < dep.replaces.length; i++) { + const rep = dep.replaces[i]; + source.replace(rep.range[0], rep.range[1] - 1, rep.value); + } + } + source.replace(dep.valueRange[1], dep.range[1] - 1, ")"); + // TODO webpack 5 remove `prepend` it's no longer used + source.replace( + dep.range[0], + dep.valueRange[0] - 1, + `${moduleExports}.resolve(${ + typeof dep.prepend === "string" ? JSON.stringify(dep.prepend) : "" + }` + ); + } else { + source.replace( + dep.range[0], + dep.range[1] - 1, + `${moduleExports}.resolve` + ); + } + } else { + source.replace(dep.range[0], dep.range[1] - 1, moduleExports); + } + } +} +module.exports = ContextDependencyTemplateAsId; diff --git a/node_modules/webpack/lib/dependencies/ContextDependencyTemplateAsRequireCall.js b/node_modules/webpack/lib/dependencies/ContextDependencyTemplateAsRequireCall.js index eeb135f38..6d833ac83 100644 --- a/node_modules/webpack/lib/dependencies/ContextDependencyTemplateAsRequireCall.js +++ b/node_modules/webpack/lib/dependencies/ContextDependencyTemplateAsRequireCall.js @@ -1,34 +1,39 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-class ContextDependencyTemplateAsRequireCall {
-
- apply(dep, source, outputOptions, requestShortener) {
- const comment = outputOptions.pathinfo ?
- "/*! " + requestShortener.shorten(dep.request) + " */ " : "";
-
- const containsDeps = dep.module && dep.module.dependencies && dep.module.dependencies.length > 0;
- const isAsync = dep.module && dep.module.async;
- if(dep.module && (isAsync || containsDeps)) {
- if(dep.valueRange) {
- if(Array.isArray(dep.replaces)) {
- for(let i = 0; i < dep.replaces.length; i++) {
- const rep = dep.replaces[i];
- source.replace(rep.range[0], rep.range[1] - 1, rep.value);
- }
- }
- source.replace(dep.valueRange[1], dep.range[1] - 1, ")");
- source.replace(dep.range[0], dep.valueRange[0] - 1, "__webpack_require__(" + comment + JSON.stringify(dep.module.id) + ")(" + (typeof dep.prepend === "string" ? JSON.stringify(dep.prepend) : "") + "");
- } else {
- source.replace(dep.range[0], dep.range[1] - 1, "__webpack_require__(" + comment + JSON.stringify(dep.module.id) + ")");
- }
- } else {
- const content = require("./WebpackMissingModule").module(dep.request);
- source.replace(dep.range[0], dep.range[1] - 1, content);
- }
- }
-}
-module.exports = ContextDependencyTemplateAsRequireCall;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +class ContextDependencyTemplateAsRequireCall { + apply(dep, source, runtime) { + const moduleExports = runtime.moduleExports({ + module: dep.module, + request: dep.request + }); + + if (dep.module) { + if (dep.valueRange) { + if (Array.isArray(dep.replaces)) { + for (let i = 0; i < dep.replaces.length; i++) { + const rep = dep.replaces[i]; + source.replace(rep.range[0], rep.range[1] - 1, rep.value); + } + } + source.replace(dep.valueRange[1], dep.range[1] - 1, ")"); + // TODO webpack 5 remove `prepend` it's no longer used + source.replace( + dep.range[0], + dep.valueRange[0] - 1, + `${moduleExports}(${ + typeof dep.prepend === "string" ? JSON.stringify(dep.prepend) : "" + }` + ); + } else { + source.replace(dep.range[0], dep.range[1] - 1, moduleExports); + } + } else { + source.replace(dep.range[0], dep.range[1] - 1, moduleExports); + } + } +} +module.exports = ContextDependencyTemplateAsRequireCall; diff --git a/node_modules/webpack/lib/dependencies/ContextElementDependency.js b/node_modules/webpack/lib/dependencies/ContextElementDependency.js index 8e5fafe52..258770490 100644 --- a/node_modules/webpack/lib/dependencies/ContextElementDependency.js +++ b/node_modules/webpack/lib/dependencies/ContextElementDependency.js @@ -1,21 +1,21 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const ModuleDependency = require("./ModuleDependency");
-
-class ContextElementDependency extends ModuleDependency {
- constructor(request, userRequest) {
- super(request);
- if(userRequest) {
- this.userRequest = userRequest;
- }
- }
-
- get type() {
- return "context element";
- }
-}
-
-module.exports = ContextElementDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const ModuleDependency = require("./ModuleDependency"); + +class ContextElementDependency extends ModuleDependency { + constructor(request, userRequest) { + super(request); + if (userRequest) { + this.userRequest = userRequest; + } + } + + get type() { + return "context element"; + } +} + +module.exports = ContextElementDependency; diff --git a/node_modules/webpack/lib/dependencies/CriticalDependencyWarning.js b/node_modules/webpack/lib/dependencies/CriticalDependencyWarning.js index 990109782..43bd5686e 100644 --- a/node_modules/webpack/lib/dependencies/CriticalDependencyWarning.js +++ b/node_modules/webpack/lib/dependencies/CriticalDependencyWarning.js @@ -1,20 +1,20 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const WebpackError = require("../WebpackError");
-
-class CriticalDependencyWarning extends WebpackError {
- constructor(message) {
- super();
-
- this.name = "CriticalDependencyWarning";
- this.message = "Critical dependency: " + message;
-
- Error.captureStackTrace(this, this.constructor);
- }
-}
-
-module.exports = CriticalDependencyWarning;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const WebpackError = require("../WebpackError"); + +class CriticalDependencyWarning extends WebpackError { + constructor(message) { + super(); + + this.name = "CriticalDependencyWarning"; + this.message = "Critical dependency: " + message; + + Error.captureStackTrace(this, this.constructor); + } +} + +module.exports = CriticalDependencyWarning; diff --git a/node_modules/webpack/lib/dependencies/DelegatedExportsDependency.js b/node_modules/webpack/lib/dependencies/DelegatedExportsDependency.js index ad36acbe4..fcacedb42 100644 --- a/node_modules/webpack/lib/dependencies/DelegatedExportsDependency.js +++ b/node_modules/webpack/lib/dependencies/DelegatedExportsDependency.js @@ -1,33 +1,33 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const NullDependency = require("./NullDependency");
-
-class DelegatedExportsDependency extends NullDependency {
- constructor(originModule, exports) {
- super();
- this.originModule = originModule;
- this.exports = exports;
- }
-
- get type() {
- return "delegated exports";
- }
-
- getReference() {
- return {
- module: this.originModule,
- importedNames: true
- };
- }
-
- getExports() {
- return {
- exports: this.exports
- };
- }
-}
-
-module.exports = DelegatedExportsDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const DependencyReference = require("./DependencyReference"); +const NullDependency = require("./NullDependency"); + +class DelegatedExportsDependency extends NullDependency { + constructor(originModule, exports) { + super(); + this.originModule = originModule; + this.exports = exports; + } + + get type() { + return "delegated exports"; + } + + getReference() { + return new DependencyReference(this.originModule, true, false); + } + + getExports() { + return { + exports: this.exports, + dependencies: undefined + }; + } +} + +module.exports = DelegatedExportsDependency; diff --git a/node_modules/webpack/lib/dependencies/DelegatedSourceDependency.js b/node_modules/webpack/lib/dependencies/DelegatedSourceDependency.js index 86341d59a..7b0b9de5e 100644 --- a/node_modules/webpack/lib/dependencies/DelegatedSourceDependency.js +++ b/node_modules/webpack/lib/dependencies/DelegatedSourceDependency.js @@ -1,18 +1,18 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const ModuleDependency = require("./ModuleDependency");
-
-class DelegatedSourceDependency extends ModuleDependency {
- constructor(request) {
- super(request);
- }
-
- get type() {
- return "delegated source";
- }
-}
-
-module.exports = DelegatedSourceDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const ModuleDependency = require("./ModuleDependency"); + +class DelegatedSourceDependency extends ModuleDependency { + constructor(request) { + super(request); + } + + get type() { + return "delegated source"; + } +} + +module.exports = DelegatedSourceDependency; diff --git a/node_modules/webpack/lib/dependencies/DepBlockHelpers.js b/node_modules/webpack/lib/dependencies/DepBlockHelpers.js deleted file mode 100644 index c1e48a3a5..000000000 --- a/node_modules/webpack/lib/dependencies/DepBlockHelpers.js +++ /dev/null @@ -1,39 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const DepBlockHelpers = exports;
-
-DepBlockHelpers.getLoadDepBlockWrapper = (depBlock, outputOptions, requestShortener, name) => {
- const promiseCode = DepBlockHelpers.getDepBlockPromise(depBlock, outputOptions, requestShortener, name);
- return [
- promiseCode + ".then(",
- ").catch(",
- ")"
- ];
-};
-
-DepBlockHelpers.getDepBlockPromise = (depBlock, outputOptions, requestShortener, name) => {
- if(depBlock.chunks) {
- const chunks = depBlock.chunks.filter(chunk => !chunk.hasRuntime() && chunk.id !== null);
- const pathChunkCheck = outputOptions.pathinfo && depBlock.chunkName;
- const shortChunkName = requestShortener.shorten(depBlock.chunkName);
- const chunkReason = asComment(depBlock.chunkReason);
- const requireChunkId = chunk => "__webpack_require__.e(" + JSON.stringify(chunk.id) + ")";
- name = asComment(name);
- if(chunks.length === 1) {
- const chunkId = JSON.stringify(chunks[0].id);
- return `__webpack_require__.e${name}(${chunkId}${pathChunkCheck ? "/*! " + shortChunkName + " */" : ""}${chunkReason})`;
- } else if(chunks.length > 0) {
- return `Promise.all${name}(${pathChunkCheck ? "/*! " + shortChunkName + " */" : ""}[${chunks.map(requireChunkId).join(", ")}])`;
- }
- }
- return "new Promise(function(resolve) { resolve(); })";
-};
-
-function asComment(str) {
- if(!str) return "";
- return `/* ${str} */`;
-}
diff --git a/node_modules/webpack/lib/dependencies/DllEntryDependency.js b/node_modules/webpack/lib/dependencies/DllEntryDependency.js index 113249de8..47c6acc0a 100644 --- a/node_modules/webpack/lib/dependencies/DllEntryDependency.js +++ b/node_modules/webpack/lib/dependencies/DllEntryDependency.js @@ -1,20 +1,20 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const Dependency = require("../Dependency");
-
-class DllEntryDependency extends Dependency {
- constructor(dependencies, name) {
- super();
- this.dependencies = dependencies;
- this.name = name;
- }
-
- get type() {
- return "dll entry";
- }
-}
-
-module.exports = DllEntryDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const Dependency = require("../Dependency"); + +class DllEntryDependency extends Dependency { + constructor(dependencies, name) { + super(); + this.dependencies = dependencies; + this.name = name; + } + + get type() { + return "dll entry"; + } +} + +module.exports = DllEntryDependency; diff --git a/node_modules/webpack/lib/dependencies/HarmonyAcceptDependency.js b/node_modules/webpack/lib/dependencies/HarmonyAcceptDependency.js index 91998126a..f152efb8f 100644 --- a/node_modules/webpack/lib/dependencies/HarmonyAcceptDependency.js +++ b/node_modules/webpack/lib/dependencies/HarmonyAcceptDependency.js @@ -1,42 +1,45 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const NullDependency = require("./NullDependency");
-const makeHarmonyImportStatement = require("./HarmonyImportDependency").makeImportStatement;
-
-class HarmonyAcceptDependency extends NullDependency {
- constructor(range, dependencies, hasCallback) {
- super();
- this.range = range;
- this.dependencies = dependencies;
- this.hasCallback = hasCallback;
- }
-
- get type() {
- return "accepted harmony modules";
- }
-}
-
-HarmonyAcceptDependency.Template = class HarmonyAcceptDependencyTemplate {
- apply(dep, source, outputOptions, requestShortener) {
- const content = dep.dependencies
- .map(dependency => makeHarmonyImportStatement(
- false,
- dependency,
- outputOptions,
- requestShortener
- )).join("");
-
- if(dep.hasCallback) {
- source.insert(dep.range[0], `function(__WEBPACK_OUTDATED_DEPENDENCIES__) { ${content}(`);
- source.insert(dep.range[1], ")(__WEBPACK_OUTDATED_DEPENDENCIES__); }");
- return;
- }
-
- source.insert(dep.range[1] - 0.5, `, function() { ${content} }`);
- }
-};
-
-module.exports = HarmonyAcceptDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const NullDependency = require("./NullDependency"); +const HarmonyImportDependency = require("./HarmonyImportDependency"); + +class HarmonyAcceptDependency extends NullDependency { + constructor(range, dependencies, hasCallback) { + super(); + this.range = range; + this.dependencies = dependencies; + this.hasCallback = hasCallback; + } + + get type() { + return "accepted harmony modules"; + } +} + +HarmonyAcceptDependency.Template = class HarmonyAcceptDependencyTemplate { + apply(dep, source, runtime) { + const content = dep.dependencies + .filter(dependency => + HarmonyImportDependency.Template.isImportEmitted(dependency, source) + ) + .map(dependency => dependency.getImportStatement(true, runtime)) + .join(""); + + if (dep.hasCallback) { + source.insert( + dep.range[0], + `function(__WEBPACK_OUTDATED_DEPENDENCIES__) { ${content}(` + ); + source.insert(dep.range[1], ")(__WEBPACK_OUTDATED_DEPENDENCIES__); }"); + return; + } + + source.insert(dep.range[1] - 0.5, `, function() { ${content} }`); + } +}; + +module.exports = HarmonyAcceptDependency; diff --git a/node_modules/webpack/lib/dependencies/HarmonyAcceptImportDependency.js b/node_modules/webpack/lib/dependencies/HarmonyAcceptImportDependency.js index 8b0689ad7..62bd00cf4 100644 --- a/node_modules/webpack/lib/dependencies/HarmonyAcceptImportDependency.js +++ b/node_modules/webpack/lib/dependencies/HarmonyAcceptImportDependency.js @@ -1,22 +1,23 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const HarmonyImportDependency = require("./HarmonyImportDependency");
-
-class HarmonyAcceptImportDependency extends HarmonyImportDependency {
- constructor(request, importedVar, range) {
- super(request, importedVar, range);
- }
-
- get type() {
- return "harmony accept";
- }
-}
-
-HarmonyAcceptImportDependency.Template = class HarmonyAcceptImportDependencyTemplate {
- apply(dep, source, outputOptions, requestShortener) {}
-};
-
-module.exports = HarmonyAcceptImportDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const HarmonyImportDependency = require("./HarmonyImportDependency"); + +class HarmonyAcceptImportDependency extends HarmonyImportDependency { + constructor(request, originModule, parserScope) { + super(request, originModule, NaN, parserScope); + this.weak = true; + } + + get type() { + return "harmony accept"; + } +} + +HarmonyAcceptImportDependency.Template = class HarmonyAcceptImportDependencyTemplate extends HarmonyImportDependency.Template { + apply(dep, source, runtime) {} +}; + +module.exports = HarmonyAcceptImportDependency; diff --git a/node_modules/webpack/lib/dependencies/HarmonyCompatibilityDependency.js b/node_modules/webpack/lib/dependencies/HarmonyCompatibilityDependency.js index 8bd7bb708..d6febb5ac 100644 --- a/node_modules/webpack/lib/dependencies/HarmonyCompatibilityDependency.js +++ b/node_modules/webpack/lib/dependencies/HarmonyCompatibilityDependency.js @@ -1,30 +1,31 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const NullDependency = require("./NullDependency");
-
-class HarmonyCompatibilityDependency extends NullDependency {
- constructor(originModule) {
- super();
- this.originModule = originModule;
- }
-
- get type() {
- return "harmony export header";
- }
-}
-
-HarmonyCompatibilityDependency.Template = class HarmonyExportDependencyTemplate {
- apply(dep, source) {
- const usedExports = dep.originModule.usedExports;
- if(usedExports && !Array.isArray(usedExports)) {
- const exportName = dep.originModule.exportsArgument || "exports";
- const content = `Object.defineProperty(${exportName}, "__esModule", { value: true });\n`;
- source.insert(-10, content);
- }
- }
-};
-
-module.exports = HarmonyCompatibilityDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const NullDependency = require("./NullDependency"); + +class HarmonyCompatibilityDependency extends NullDependency { + constructor(originModule) { + super(); + this.originModule = originModule; + } + + get type() { + return "harmony export header"; + } +} + +HarmonyCompatibilityDependency.Template = class HarmonyExportDependencyTemplate { + apply(dep, source, runtime) { + const usedExports = dep.originModule.usedExports; + if (usedExports !== false && !Array.isArray(usedExports)) { + const content = runtime.defineEsModuleFlagStatement({ + exportsArgument: dep.originModule.exportsArgument + }); + source.insert(-10, content); + } + } +}; + +module.exports = HarmonyCompatibilityDependency; diff --git a/node_modules/webpack/lib/dependencies/HarmonyDetectionParserPlugin.js b/node_modules/webpack/lib/dependencies/HarmonyDetectionParserPlugin.js index 4de7afb58..062ec21a6 100644 --- a/node_modules/webpack/lib/dependencies/HarmonyDetectionParserPlugin.js +++ b/node_modules/webpack/lib/dependencies/HarmonyDetectionParserPlugin.js @@ -1,56 +1,92 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const HarmonyCompatibilityDependency = require("./HarmonyCompatibilityDependency");
-
-module.exports = class HarmonyDetectionParserPlugin {
- apply(parser) {
- parser.plugin("program", (ast) => {
- const isHarmony = ast.body.some(statement => {
- return /^(Import|Export).*Declaration$/.test(statement.type);
- });
- if(isHarmony) {
- const module = parser.state.module;
- const dep = new HarmonyCompatibilityDependency(module);
- dep.loc = {
- start: {
- line: -1,
- column: 0
- },
- end: {
- line: -1,
- column: 0
- },
- index: -2
- };
- module.addDependency(dep);
- module.meta.harmonyModule = true;
- module.strict = true;
- module.exportsArgument = "__webpack_exports__";
- }
- });
- const nonHarmonyIdentifiers = ["define", "exports"];
- nonHarmonyIdentifiers.forEach(identifer => {
- parser.plugin(`evaluate typeof ${identifer}`, nullInHarmony);
- parser.plugin(`typeof ${identifer}`, skipInHarmony);
- parser.plugin(`evaluate ${identifer}`, nullInHarmony);
- parser.plugin(`expression ${identifer}`, skipInHarmony);
- parser.plugin(`call ${identifer}`, skipInHarmony);
- });
-
- function skipInHarmony() {
- const module = this.state.module;
- if(module && module.meta && module.meta.harmonyModule)
- return true;
- }
-
- function nullInHarmony() {
- const module = this.state.module;
- if(module && module.meta && module.meta.harmonyModule)
- return null;
- }
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const HarmonyCompatibilityDependency = require("./HarmonyCompatibilityDependency"); +const HarmonyInitDependency = require("./HarmonyInitDependency"); + +module.exports = class HarmonyDetectionParserPlugin { + apply(parser) { + parser.hooks.program.tap("HarmonyDetectionParserPlugin", ast => { + const isStrictHarmony = parser.state.module.type === "javascript/esm"; + const isHarmony = + isStrictHarmony || + ast.body.some(statement => { + return /^(Import|Export).*Declaration$/.test(statement.type); + }); + if (isHarmony) { + const module = parser.state.module; + const compatDep = new HarmonyCompatibilityDependency(module); + compatDep.loc = { + start: { + line: -1, + column: 0 + }, + end: { + line: -1, + column: 0 + }, + index: -3 + }; + module.addDependency(compatDep); + const initDep = new HarmonyInitDependency(module); + initDep.loc = { + start: { + line: -1, + column: 0 + }, + end: { + line: -1, + column: 0 + }, + index: -2 + }; + module.addDependency(initDep); + parser.state.harmonyParserScope = parser.state.harmonyParserScope || {}; + parser.scope.isStrict = true; + module.buildMeta.exportsType = "namespace"; + module.buildInfo.strict = true; + module.buildInfo.exportsArgument = "__webpack_exports__"; + if (isStrictHarmony) { + module.buildMeta.strictHarmonyModule = true; + module.buildInfo.moduleArgument = "__webpack_module__"; + } + } + }); + + const skipInHarmony = () => { + const module = parser.state.module; + if (module && module.buildMeta && module.buildMeta.exportsType) { + return true; + } + }; + + const nullInHarmony = () => { + const module = parser.state.module; + if (module && module.buildMeta && module.buildMeta.exportsType) { + return null; + } + }; + + const nonHarmonyIdentifiers = ["define", "exports"]; + for (const identifer of nonHarmonyIdentifiers) { + parser.hooks.evaluateTypeof + .for(identifer) + .tap("HarmonyDetectionParserPlugin", nullInHarmony); + parser.hooks.typeof + .for(identifer) + .tap("HarmonyDetectionParserPlugin", skipInHarmony); + parser.hooks.evaluate + .for(identifer) + .tap("HarmonyDetectionParserPlugin", nullInHarmony); + parser.hooks.expression + .for(identifer) + .tap("HarmonyDetectionParserPlugin", skipInHarmony); + parser.hooks.call + .for(identifer) + .tap("HarmonyDetectionParserPlugin", skipInHarmony); + } + } +}; diff --git a/node_modules/webpack/lib/dependencies/HarmonyExportDependencyParserPlugin.js b/node_modules/webpack/lib/dependencies/HarmonyExportDependencyParserPlugin.js index f7072ebac..6ab0c0fe1 100644 --- a/node_modules/webpack/lib/dependencies/HarmonyExportDependencyParserPlugin.js +++ b/node_modules/webpack/lib/dependencies/HarmonyExportDependencyParserPlugin.js @@ -1,87 +1,154 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const HarmonyExportExpressionDependency = require("./HarmonyExportExpressionDependency");
-const HarmonyExportHeaderDependency = require("./HarmonyExportHeaderDependency");
-const HarmonyExportSpecifierDependency = require("./HarmonyExportSpecifierDependency");
-const HarmonyExportImportedSpecifierDependency = require("./HarmonyExportImportedSpecifierDependency");
-const HarmonyImportDependency = require("./HarmonyImportDependency");
-const HarmonyModulesHelpers = require("./HarmonyModulesHelpers");
-
-module.exports = class HarmonyExportDependencyParserPlugin {
- apply(parser) {
- parser.plugin("export", statement => {
- const dep = new HarmonyExportHeaderDependency(statement.declaration && statement.declaration.range, statement.range);
- dep.loc = Object.create(statement.loc);
- dep.loc.index = -1;
- parser.state.current.addDependency(dep);
- return true;
- });
- parser.plugin("export import", (statement, source) => {
- const dep = new HarmonyImportDependency(source, HarmonyModulesHelpers.getNewModuleVar(parser.state, source), statement.range);
- dep.loc = Object.create(statement.loc);
- dep.loc.index = -1;
- parser.state.current.addDependency(dep);
- parser.state.lastHarmonyImport = dep;
- return true;
- });
- parser.plugin("export expression", (statement, expr) => {
- const dep = new HarmonyExportExpressionDependency(parser.state.module, expr.range, statement.range);
- dep.loc = Object.create(statement.loc);
- dep.loc.index = -1;
- parser.state.current.addDependency(dep);
- return true;
- });
- parser.plugin("export declaration", statement => {});
- parser.plugin("export specifier", (statement, id, name, idx) => {
- const rename = parser.scope.renames[`$${id}`];
- let dep;
- const harmonyNamedExports = parser.state.harmonyNamedExports = parser.state.harmonyNamedExports || new Set();
- harmonyNamedExports.add(name);
- if(rename === "imported var") {
- const settings = parser.state.harmonySpecifier[`$${id}`];
- dep = new HarmonyExportImportedSpecifierDependency(parser.state.module, settings[0], settings[1], settings[2], name, harmonyNamedExports, null);
- } else {
- const immutable = statement.declaration && isImmutableStatement(statement.declaration);
- const hoisted = statement.declaration && isHoistedStatement(statement.declaration);
- dep = new HarmonyExportSpecifierDependency(parser.state.module, id, name, !immutable || hoisted ? -2 : (statement.range[1] + 0.5), immutable);
- }
- dep.loc = Object.create(statement.loc);
- dep.loc.index = idx;
- parser.state.current.addDependency(dep);
- return true;
- });
- parser.plugin("export import specifier", (statement, source, id, name, idx) => {
- const harmonyNamedExports = parser.state.harmonyNamedExports = parser.state.harmonyNamedExports || new Set();
- let harmonyStarExports = null;
- if(name) {
- harmonyNamedExports.add(name);
- } else {
- harmonyStarExports = parser.state.harmonyStarExports = parser.state.harmonyStarExports || [];
- }
- const dep = new HarmonyExportImportedSpecifierDependency(parser.state.module, parser.state.lastHarmonyImport, HarmonyModulesHelpers.getModuleVar(parser.state, source), id, name, harmonyNamedExports, harmonyStarExports && harmonyStarExports.slice());
- if(harmonyStarExports) {
- harmonyStarExports.push(dep);
- }
- dep.loc = Object.create(statement.loc);
- dep.loc.index = idx;
- parser.state.current.addDependency(dep);
- return true;
- });
- }
-};
-
-function isImmutableStatement(statement) {
- if(statement.type === "FunctionDeclaration") return true;
- if(statement.type === "ClassDeclaration") return true;
- if(statement.type === "VariableDeclaration" && statement.kind === "const") return true;
- return false;
-}
-
-function isHoistedStatement(statement) {
- if(statement.type === "FunctionDeclaration") return true;
- return false;
-}
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const HarmonyExportExpressionDependency = require("./HarmonyExportExpressionDependency"); +const HarmonyImportSideEffectDependency = require("./HarmonyImportSideEffectDependency"); +const HarmonyExportHeaderDependency = require("./HarmonyExportHeaderDependency"); +const HarmonyExportSpecifierDependency = require("./HarmonyExportSpecifierDependency"); +const HarmonyExportImportedSpecifierDependency = require("./HarmonyExportImportedSpecifierDependency"); +const ConstDependency = require("./ConstDependency"); + +module.exports = class HarmonyExportDependencyParserPlugin { + constructor(moduleOptions) { + this.strictExportPresence = moduleOptions.strictExportPresence; + } + + apply(parser) { + parser.hooks.export.tap( + "HarmonyExportDependencyParserPlugin", + statement => { + const dep = new HarmonyExportHeaderDependency( + statement.declaration && statement.declaration.range, + statement.range + ); + dep.loc = Object.create(statement.loc); + dep.loc.index = -1; + parser.state.current.addDependency(dep); + return true; + } + ); + parser.hooks.exportImport.tap( + "HarmonyExportDependencyParserPlugin", + (statement, source) => { + parser.state.lastHarmonyImportOrder = + (parser.state.lastHarmonyImportOrder || 0) + 1; + const clearDep = new ConstDependency("", statement.range); + clearDep.loc = Object.create(statement.loc); + clearDep.loc.index = -1; + parser.state.current.addDependency(clearDep); + const sideEffectDep = new HarmonyImportSideEffectDependency( + source, + parser.state.module, + parser.state.lastHarmonyImportOrder, + parser.state.harmonyParserScope + ); + sideEffectDep.loc = Object.create(statement.loc); + sideEffectDep.loc.index = -1; + parser.state.current.addDependency(sideEffectDep); + return true; + } + ); + parser.hooks.exportExpression.tap( + "HarmonyExportDependencyParserPlugin", + (statement, expr) => { + const comments = parser.getComments([ + statement.range[0], + expr.range[0] + ]); + const dep = new HarmonyExportExpressionDependency( + parser.state.module, + expr.range, + statement.range, + comments + .map(c => { + switch (c.type) { + case "Block": + return `/*${c.value}*/`; + case "Line": + return `//${c.value}\n`; + } + return ""; + }) + .join("") + ); + dep.loc = Object.create(statement.loc); + dep.loc.index = -1; + parser.state.current.addDependency(dep); + return true; + } + ); + parser.hooks.exportDeclaration.tap( + "HarmonyExportDependencyParserPlugin", + statement => {} + ); + parser.hooks.exportSpecifier.tap( + "HarmonyExportDependencyParserPlugin", + (statement, id, name, idx) => { + const rename = parser.scope.renames.get(id); + let dep; + const harmonyNamedExports = (parser.state.harmonyNamedExports = + parser.state.harmonyNamedExports || new Set()); + harmonyNamedExports.add(name); + if (rename === "imported var") { + const settings = parser.state.harmonySpecifier.get(id); + dep = new HarmonyExportImportedSpecifierDependency( + settings.source, + parser.state.module, + settings.sourceOrder, + parser.state.harmonyParserScope, + settings.id, + name, + harmonyNamedExports, + null, + this.strictExportPresence + ); + } else { + dep = new HarmonyExportSpecifierDependency( + parser.state.module, + id, + name + ); + } + dep.loc = Object.create(statement.loc); + dep.loc.index = idx; + parser.state.current.addDependency(dep); + return true; + } + ); + parser.hooks.exportImportSpecifier.tap( + "HarmonyExportDependencyParserPlugin", + (statement, source, id, name, idx) => { + const harmonyNamedExports = (parser.state.harmonyNamedExports = + parser.state.harmonyNamedExports || new Set()); + let harmonyStarExports = null; + if (name) { + harmonyNamedExports.add(name); + } else { + harmonyStarExports = parser.state.harmonyStarExports = + parser.state.harmonyStarExports || []; + } + const dep = new HarmonyExportImportedSpecifierDependency( + source, + parser.state.module, + parser.state.lastHarmonyImportOrder, + parser.state.harmonyParserScope, + id, + name, + harmonyNamedExports, + harmonyStarExports && harmonyStarExports.slice(), + this.strictExportPresence + ); + if (harmonyStarExports) { + harmonyStarExports.push(dep); + } + dep.loc = Object.create(statement.loc); + dep.loc.index = idx; + parser.state.current.addDependency(dep); + return true; + } + ); + } +}; diff --git a/node_modules/webpack/lib/dependencies/HarmonyExportExpressionDependency.js b/node_modules/webpack/lib/dependencies/HarmonyExportExpressionDependency.js index c2d90847b..dfb499add 100644 --- a/node_modules/webpack/lib/dependencies/HarmonyExportExpressionDependency.js +++ b/node_modules/webpack/lib/dependencies/HarmonyExportExpressionDependency.js @@ -1,50 +1,58 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const NullDependency = require("./NullDependency");
-
-class HarmonyExportExpressionDependency extends NullDependency {
- constructor(originModule, range, rangeStatement) {
- super();
- this.originModule = originModule;
- this.range = range;
- this.rangeStatement = rangeStatement;
- }
-
- get type() {
- return "harmony export expression";
- }
-
- getExports() {
- return {
- exports: ["default"]
- };
- }
-}
-
-HarmonyExportExpressionDependency.Template = class HarmonyExportDependencyTemplate {
- apply(dep, source) {
- const used = dep.originModule.isUsed("default");
- const content = this.getContent(dep.originModule, used);
-
- if(dep.range) {
- source.replace(dep.rangeStatement[0], dep.range[0] - 1, content + "(");
- source.replace(dep.range[1], dep.rangeStatement[1] - 1, ");");
- return;
- }
-
- source.replace(dep.rangeStatement[0], dep.rangeStatement[1] - 1, content);
- }
-
- getContent(module, used) {
- const exportsName = module.exportsArgument || "exports";
- if(used) {
- return `/* harmony default export */ ${exportsName}[${JSON.stringify(used)}] = `;
- }
- return "/* unused harmony default export */ var _unused_webpack_default_export = ";
- }
-};
-
-module.exports = HarmonyExportExpressionDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const NullDependency = require("./NullDependency"); + +class HarmonyExportExpressionDependency extends NullDependency { + constructor(originModule, range, rangeStatement, prefix) { + super(); + this.originModule = originModule; + this.range = range; + this.rangeStatement = rangeStatement; + this.prefix = prefix; + } + + get type() { + return "harmony export expression"; + } + + getExports() { + return { + exports: ["default"], + dependencies: undefined + }; + } +} + +HarmonyExportExpressionDependency.Template = class HarmonyExportDependencyTemplate { + apply(dep, source) { + const used = dep.originModule.isUsed("default"); + const content = this.getContent(dep.originModule, used); + + if (dep.range) { + source.replace( + dep.rangeStatement[0], + dep.range[0] - 1, + content + "(" + dep.prefix + ); + source.replace(dep.range[1], dep.rangeStatement[1] - 1, ");"); + return; + } + + source.replace(dep.rangeStatement[0], dep.rangeStatement[1] - 1, content); + } + + getContent(module, used) { + const exportsName = module.exportsArgument; + if (used) { + return `/* harmony default export */ ${exportsName}[${JSON.stringify( + used + )}] = `; + } + return "/* unused harmony default export */ var _unused_webpack_default_export = "; + } +}; + +module.exports = HarmonyExportExpressionDependency; diff --git a/node_modules/webpack/lib/dependencies/HarmonyExportHeaderDependency.js b/node_modules/webpack/lib/dependencies/HarmonyExportHeaderDependency.js index 86033ce95..a0e9918bd 100644 --- a/node_modules/webpack/lib/dependencies/HarmonyExportHeaderDependency.js +++ b/node_modules/webpack/lib/dependencies/HarmonyExportHeaderDependency.js @@ -1,28 +1,30 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const NullDependency = require("./NullDependency");
-
-class HarmonyExportHeaderDependency extends NullDependency {
- constructor(range, rangeStatement) {
- super();
- this.range = range;
- this.rangeStatement = rangeStatement;
- }
-
- get type() {
- return "harmony export header";
- }
-}
-
-HarmonyExportHeaderDependency.Template = class HarmonyExportDependencyTemplate {
- apply(dep, source) {
- const content = "";
- const replaceUntil = dep.range ? dep.range[0] - 1 : dep.rangeStatement[1] - 1;
- source.replace(dep.rangeStatement[0], replaceUntil, content);
- }
-};
-
-module.exports = HarmonyExportHeaderDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const NullDependency = require("./NullDependency"); + +class HarmonyExportHeaderDependency extends NullDependency { + constructor(range, rangeStatement) { + super(); + this.range = range; + this.rangeStatement = rangeStatement; + } + + get type() { + return "harmony export header"; + } +} + +HarmonyExportHeaderDependency.Template = class HarmonyExportDependencyTemplate { + apply(dep, source) { + const content = ""; + const replaceUntil = dep.range + ? dep.range[0] - 1 + : dep.rangeStatement[1] - 1; + source.replace(dep.rangeStatement[0], replaceUntil, content); + } +}; + +module.exports = HarmonyExportHeaderDependency; diff --git a/node_modules/webpack/lib/dependencies/HarmonyExportImportedSpecifierDependency.js b/node_modules/webpack/lib/dependencies/HarmonyExportImportedSpecifierDependency.js index cb1b892d2..1965d0dbb 100644 --- a/node_modules/webpack/lib/dependencies/HarmonyExportImportedSpecifierDependency.js +++ b/node_modules/webpack/lib/dependencies/HarmonyExportImportedSpecifierDependency.js @@ -1,285 +1,645 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const NullDependency = require("./NullDependency");
-
-class HarmonyExportImportedSpecifierDependency extends NullDependency {
- constructor(originModule, importDependency, importedVar, id, name, activeExports, otherStarExports) {
- super();
- this.originModule = originModule;
- this.importDependency = importDependency;
- this.importedVar = importedVar;
- this.id = id;
- this.name = name;
- this.activeExports = activeExports;
- this.otherStarExports = otherStarExports;
- }
-
- get type() {
- return "harmony export imported specifier";
- }
-
- getReference() {
- const name = this.name;
- const used = this.originModule.isUsed(name);
- const importedModule = this.importDependency.module;
-
- if(!importedModule || !used || !this.originModule.usedExports) return null;
-
- const hasUsedExports = Array.isArray(this.originModule.usedExports);
-
- if(name) {
- const nameIsNotInUsedExports = hasUsedExports && this.originModule.usedExports.indexOf(name) < 0;
- if(nameIsNotInUsedExports) return null;
-
- // export { name as name }
- if(this.id) {
- return {
- module: importedModule,
- importedNames: [this.id]
- };
- }
-
- // export { * as name }
- return {
- module: importedModule,
- importedNames: true
- };
- }
-
- const hasProvidedExports = Array.isArray(importedModule.providedExports);
- const activeFromOtherStarExports = this._discoverActiveExportsFromOtherStartExports();
-
- // export *
- if(hasUsedExports) {
- // reexport * with known used exports
- const importedNames = this.originModule.usedExports.filter(id => {
- if(id === "default") return false;
- if(this.activeExports.has(id)) return false;
- if(activeFromOtherStarExports.has(id)) return false;
- if(hasProvidedExports && importedModule.providedExports.indexOf(id) < 0) return false;
-
- return true;
- });
-
- return {
- module: importedModule,
- importedNames
- };
- }
-
- if(hasProvidedExports) {
- return {
- module: importedModule,
- importedNames: importedModule.providedExports.filter(id => {
- if(id === "default") return false;
- if(this.activeExports.has(id)) return false;
- if(activeFromOtherStarExports.has(id)) return false;
-
- return true;
- })
- };
- }
-
- return {
- module: importedModule,
- importedNames: true,
- };
- }
-
- _discoverActiveExportsFromOtherStartExports() {
- if(!this.otherStarExports)
- return new Set();
- const result = new Set();
- // try to learn impossible exports from other star exports with provided exports
- for(const otherStarExport of this.otherStarExports) {
- const otherImportedModule = otherStarExport.importDependency.module;
- if(otherImportedModule && Array.isArray(otherImportedModule.providedExports)) {
- for(const exportName of otherImportedModule.providedExports)
- result.add(exportName);
- }
- }
- return result;
- }
-
- getExports() {
- if(this.name) {
- return {
- exports: [this.name]
- };
- }
-
- const importedModule = this.importDependency.module;
-
- if(!importedModule) {
- // no imported module available
- return {
- exports: null
- };
- }
-
- if(Array.isArray(importedModule.providedExports)) {
- return {
- exports: importedModule.providedExports.filter(id => id !== "default"),
- dependencies: [importedModule]
- };
- }
-
- if(importedModule.providedExports) {
- return {
- exports: true
- };
- }
-
- return {
- exports: null,
- dependencies: [importedModule]
- };
- }
-
- updateHash(hash) {
- super.updateHash(hash);
- const hashValue = this.getHashValue(this.importDependency.module);
- hash.update(hashValue);
- }
-
- getHashValue(importedModule) {
- if(!importedModule) {
- return "";
- }
-
- const stringifiedUsedExport = JSON.stringify(importedModule.usedExports);
- const stringifiedProvidedExport = JSON.stringify(importedModule.providedExports);
- return importedModule.used + stringifiedUsedExport + stringifiedProvidedExport;
- }
-}
-
-module.exports = HarmonyExportImportedSpecifierDependency;
-
-HarmonyExportImportedSpecifierDependency.Template = class HarmonyExportImportedSpecifierDependencyTemplate {
- apply(dep, source, outputOptions, requestShortener) {
- const content = this.getContent(dep);
- source.insert(-1, content);
- }
-
- getContent(dep) {
- const name = dep.importedVar;
- const used = dep.originModule.isUsed(dep.name);
- const importedModule = dep.importDependency.module;
- const importsExportsUnknown = !importedModule || !Array.isArray(importedModule.providedExports);
-
- const getReexportStatement = this.reexportStatementCreator(dep.originModule, importsExportsUnknown, name);
-
- // we want to rexport something, but the export isn't used
- if(!used) {
- return "/* unused harmony reexport " + dep.name + " */\n";
- }
-
- // we want to reexport the default export from a non-hamory module
- const isNotAHarmonyModule = !(importedModule && (!importedModule.meta || importedModule.meta.harmonyModule));
- if(dep.name && dep.id === "default" && isNotAHarmonyModule) {
- return "/* harmony reexport (default from non-hamory) */ " + getReexportStatement(JSON.stringify(used), null);
- }
-
- // we want to reexport a key as new key
- if(dep.name && dep.id) {
- var idUsed = importedModule && importedModule.isUsed(dep.id);
- return "/* harmony reexport (binding) */ " + getReexportStatement(JSON.stringify(used), JSON.stringify(idUsed));
- }
-
- // we want to reexport the module object as named export
- if(dep.name) {
- return "/* harmony reexport (module object) */ " + getReexportStatement(JSON.stringify(used), "");
- }
-
- const hasProvidedExports = importedModule && Array.isArray(importedModule.providedExports);
-
- const activeFromOtherStarExports = dep._discoverActiveExportsFromOtherStartExports();
-
- // we know which exports are used
- if(Array.isArray(dep.originModule.usedExports)) {
- const items = dep.originModule.usedExports.map(id => {
- if(id === "default") return;
- if(dep.activeExports.has(id)) return;
- if(importedModule.isProvided(id) === false) return;
- if(activeFromOtherStarExports.has(id)) return;
- var exportUsed = dep.originModule.isUsed(id);
- var idUsed = importedModule && importedModule.isUsed(id);
- return [exportUsed, idUsed];
- }).filter(Boolean);
-
- if(items.length === 0) {
- return "/* unused harmony namespace reexport */\n";
- }
-
- return items.map(function(item) {
- return "/* harmony namespace reexport (by used) */ " + getReexportStatement(JSON.stringify(item[0]), JSON.stringify(item[1]));
- }).join("");
- }
-
- // not sure which exports are used, but we know which are provided
- if(dep.originModule.usedExports && importedModule && hasProvidedExports) {
- const items = importedModule.providedExports.map(id => {
- if(id === "default") return;
- if(dep.activeExports.has(id)) return;
- if(activeFromOtherStarExports.has(id)) return;
- var exportUsed = dep.originModule.isUsed(id);
- var idUsed = importedModule && importedModule.isUsed(id);
- return [exportUsed, idUsed];
- }).filter(Boolean);
-
- if(items.length === 0) {
- return "/* empty harmony namespace reexport */\n";
- }
-
- return items.map(function(item) {
- return "/* harmony namespace reexport (by provided) */ " + getReexportStatement(JSON.stringify(item[0]), JSON.stringify(item[1]));
- }).join("");
- }
-
- // not sure which exports are used and provided
- if(dep.originModule.usedExports) {
- const activeExports = Array.from(dep.activeExports).concat(Array.from(activeFromOtherStarExports));
- let content = "/* harmony namespace reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in " + name + ") ";
-
- // Filter out exports which are defined by other exports
- // and filter out default export because it cannot be reexported with *
- if(activeExports.length > 0)
- content += "if(" + JSON.stringify(activeExports.concat("default")) + ".indexOf(__WEBPACK_IMPORT_KEY__) < 0) ";
- else
- content += "if(__WEBPACK_IMPORT_KEY__ !== 'default') ";
- const exportsName = dep.originModule.exportsArgument || "exports";
- return content + `(function(key) { __webpack_require__.d(${exportsName}, key, function() { return ${name}[key]; }) }(__WEBPACK_IMPORT_KEY__));\n`;
- }
-
- return "/* unused harmony reexport namespace */\n";
- }
-
- reexportStatementCreator(module, importsExportsUnknown, name) {
- const exportsName = module.exportsArgument || "exports";
- const getReexportStatement = (key, valueKey) => {
- const conditional = this.getConditional(importsExportsUnknown, valueKey, name);
- const returnValue = this.getReturnValue(valueKey);
- return `${conditional}__webpack_require__.d(${exportsName}, ${key}, function() { return ${name}${returnValue}; });\n`;
- };
- return getReexportStatement;
- }
-
- getConditional(importsExportsUnknown, valueKey, name) {
- if(!importsExportsUnknown || !valueKey) {
- return "";
- }
-
- return `if(__webpack_require__.o(${name}, ${valueKey})) `;
- }
-
- getReturnValue(valueKey) {
- if(valueKey === null) {
- return "_default.a";
- }
-
- return valueKey && "[" + valueKey + "]";
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const DependencyReference = require("./DependencyReference"); +const HarmonyImportDependency = require("./HarmonyImportDependency"); +const Template = require("../Template"); +const HarmonyLinkingError = require("../HarmonyLinkingError"); + +/** @typedef {import("../Module")} Module */ + +/** @typedef {"missing"|"unused"|"empty-star"|"reexport-non-harmony-default"|"reexport-named-default"|"reexport-namespace-object"|"reexport-non-harmony-default-strict"|"reexport-fake-namespace-object"|"rexport-non-harmony-undefined"|"safe-reexport"|"checked-reexport"|"dynamic-reexport"} ExportModeType */ + +/** @type {Map<string, string>} */ +const EMPTY_MAP = new Map(); + +class ExportMode { + /** + * @param {ExportModeType} type type of the mode + */ + constructor(type) { + /** @type {ExportModeType} */ + this.type = type; + /** @type {string|null} */ + this.name = null; + /** @type {Map<string, string>} */ + this.map = EMPTY_MAP; + /** @type {Module|null} */ + this.module = null; + /** @type {string|null} */ + this.userRequest = null; + } +} + +const EMPTY_STAR_MODE = new ExportMode("empty-star"); + +class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { + constructor( + request, + originModule, + sourceOrder, + parserScope, + id, + name, + activeExports, + otherStarExports, + strictExportPresence + ) { + super(request, originModule, sourceOrder, parserScope); + this.id = id; + this.name = name; + this.activeExports = activeExports; + this.otherStarExports = otherStarExports; + this.strictExportPresence = strictExportPresence; + } + + get type() { + return "harmony export imported specifier"; + } + + getMode(ignoreUnused) { + const name = this.name; + const id = this.id; + const used = this.originModule.isUsed(name); + const importedModule = this._module; + + if (!importedModule) { + const mode = new ExportMode("missing"); + mode.userRequest = this.userRequest; + return mode; + } + + if ( + !ignoreUnused && + (name ? !used : this.originModule.usedExports === false) + ) { + const mode = new ExportMode("unused"); + mode.name = name || "*"; + return mode; + } + + const strictHarmonyModule = this.originModule.buildMeta.strictHarmonyModule; + if (name && id === "default" && importedModule.buildMeta) { + if (!importedModule.buildMeta.exportsType) { + const mode = new ExportMode( + strictHarmonyModule + ? "reexport-non-harmony-default-strict" + : "reexport-non-harmony-default" + ); + mode.name = name; + mode.module = importedModule; + return mode; + } else if (importedModule.buildMeta.exportsType === "named") { + const mode = new ExportMode("reexport-named-default"); + mode.name = name; + mode.module = importedModule; + return mode; + } + } + + const isNotAHarmonyModule = + importedModule.buildMeta && !importedModule.buildMeta.exportsType; + if (name) { + let mode; + if (id) { + // export { name as name } + if (isNotAHarmonyModule && strictHarmonyModule) { + mode = new ExportMode("rexport-non-harmony-undefined"); + mode.name = name; + } else { + mode = new ExportMode("safe-reexport"); + mode.map = new Map([[name, id]]); + } + } else { + // export { * as name } + if (isNotAHarmonyModule && strictHarmonyModule) { + mode = new ExportMode("reexport-fake-namespace-object"); + mode.name = name; + } else { + mode = new ExportMode("reexport-namespace-object"); + mode.name = name; + } + } + mode.module = importedModule; + return mode; + } + + const hasUsedExports = Array.isArray(this.originModule.usedExports); + const hasProvidedExports = Array.isArray( + importedModule.buildMeta.providedExports + ); + const activeFromOtherStarExports = this._discoverActiveExportsFromOtherStartExports(); + + // export * + if (hasUsedExports) { + // reexport * with known used exports + if (hasProvidedExports) { + const map = new Map( + this.originModule.usedExports + .filter(id => { + if (id === "default") return false; + if (this.activeExports.has(id)) return false; + if (activeFromOtherStarExports.has(id)) return false; + if (!importedModule.buildMeta.providedExports.includes(id)) + return false; + return true; + }) + .map(item => [item, item]) + ); + + if (map.size === 0) { + return EMPTY_STAR_MODE; + } + + const mode = new ExportMode("safe-reexport"); + mode.module = importedModule; + mode.map = map; + return mode; + } + + const map = new Map( + this.originModule.usedExports + .filter(id => { + if (id === "default") return false; + if (this.activeExports.has(id)) return false; + if (activeFromOtherStarExports.has(id)) return false; + + return true; + }) + .map(item => [item, item]) + ); + + if (map.size === 0) { + return EMPTY_STAR_MODE; + } + + const mode = new ExportMode("checked-reexport"); + mode.module = importedModule; + mode.map = map; + return mode; + } + + if (hasProvidedExports) { + const map = new Map( + importedModule.buildMeta.providedExports + .filter(id => { + if (id === "default") return false; + if (this.activeExports.has(id)) return false; + if (activeFromOtherStarExports.has(id)) return false; + + return true; + }) + .map(item => [item, item]) + ); + + if (map.size === 0) { + return EMPTY_STAR_MODE; + } + + const mode = new ExportMode("safe-reexport"); + mode.module = importedModule; + mode.map = map; + return mode; + } + + const mode = new ExportMode("dynamic-reexport"); + mode.module = importedModule; + return mode; + } + + getReference() { + const mode = this.getMode(false); + + switch (mode.type) { + case "missing": + case "unused": + case "empty-star": + return null; + + case "reexport-non-harmony-default": + case "reexport-named-default": + return new DependencyReference( + mode.module, + ["default"], + false, + this.sourceOrder + ); + + case "reexport-namespace-object": + case "reexport-non-harmony-default-strict": + case "reexport-fake-namespace-object": + case "rexport-non-harmony-undefined": + return new DependencyReference( + mode.module, + true, + false, + this.sourceOrder + ); + + case "safe-reexport": + case "checked-reexport": + return new DependencyReference( + mode.module, + Array.from(mode.map.values()), + false, + this.sourceOrder + ); + + case "dynamic-reexport": + return new DependencyReference( + mode.module, + true, + false, + this.sourceOrder + ); + + default: + throw new Error(`Unknown mode ${mode.type}`); + } + } + + _discoverActiveExportsFromOtherStartExports() { + if (!this.otherStarExports) return new Set(); + const result = new Set(); + // try to learn impossible exports from other star exports with provided exports + for (const otherStarExport of this.otherStarExports) { + const otherImportedModule = otherStarExport._module; + if ( + otherImportedModule && + Array.isArray(otherImportedModule.buildMeta.providedExports) + ) { + for (const exportName of otherImportedModule.buildMeta + .providedExports) { + result.add(exportName); + } + } + } + return result; + } + + getExports() { + if (this.name) { + return { + exports: [this.name], + dependencies: undefined + }; + } + + const importedModule = this.module; + + if (!importedModule) { + // no imported module available + return { + exports: null, + dependencies: undefined + }; + } + + if (Array.isArray(importedModule.buildMeta.providedExports)) { + return { + exports: importedModule.buildMeta.providedExports.filter( + id => id !== "default" + ), + dependencies: [importedModule] + }; + } + + if (importedModule.buildMeta.providedExports) { + return { + exports: true, + dependencies: undefined + }; + } + + return { + exports: null, + dependencies: [importedModule] + }; + } + + getWarnings() { + if ( + this.strictExportPresence || + this.originModule.buildMeta.strictHarmonyModule + ) { + return []; + } + return this._getErrors(); + } + + getErrors() { + if ( + this.strictExportPresence || + this.originModule.buildMeta.strictHarmonyModule + ) { + return this._getErrors(); + } + return []; + } + + _getErrors() { + const importedModule = this._module; + if (!importedModule) { + return; + } + + if (!importedModule.buildMeta || !importedModule.buildMeta.exportsType) { + // It's not an harmony module + if ( + this.originModule.buildMeta.strictHarmonyModule && + this.id !== "default" + ) { + // In strict harmony modules we only support the default export + const exportName = this.id + ? `the named export '${this.id}'` + : "the namespace object"; + return [ + new HarmonyLinkingError( + `Can't reexport ${exportName} from non EcmaScript module (only default export is available)` + ) + ]; + } + return; + } + + if (!this.id) { + return; + } + + if (importedModule.isProvided(this.id) !== false) { + // It's provided or we are not sure + return; + } + + // We are sure that it's not provided + const idIsNotNameMessage = + this.id !== this.name ? ` (reexported as '${this.name}')` : ""; + const errorMessage = `"export '${ + this.id + }'${idIsNotNameMessage} was not found in '${this.userRequest}'`; + return [new HarmonyLinkingError(errorMessage)]; + } + + updateHash(hash) { + super.updateHash(hash); + const hashValue = this.getHashValue(this._module); + hash.update(hashValue); + } + + getHashValue(importedModule) { + if (!importedModule) { + return ""; + } + + const stringifiedUsedExport = JSON.stringify(importedModule.usedExports); + const stringifiedProvidedExport = JSON.stringify( + importedModule.buildMeta.providedExports + ); + return ( + importedModule.used + stringifiedUsedExport + stringifiedProvidedExport + ); + } +} + +module.exports = HarmonyExportImportedSpecifierDependency; + +HarmonyExportImportedSpecifierDependency.Template = class HarmonyExportImportedSpecifierDependencyTemplate extends HarmonyImportDependency.Template { + harmonyInit(dep, source, runtime, dependencyTemplates) { + super.harmonyInit(dep, source, runtime, dependencyTemplates); + const content = this.getContent(dep); + source.insert(-1, content); + } + + getHarmonyInitOrder(dep) { + if (dep.name) { + const used = dep.originModule.isUsed(dep.name); + if (!used) return NaN; + } else { + const importedModule = dep._module; + + const activeFromOtherStarExports = dep._discoverActiveExportsFromOtherStartExports(); + + if (Array.isArray(dep.originModule.usedExports)) { + // we know which exports are used + + const unused = dep.originModule.usedExports.every(id => { + if (id === "default") return true; + if (dep.activeExports.has(id)) return true; + if (importedModule.isProvided(id) === false) return true; + if (activeFromOtherStarExports.has(id)) return true; + return false; + }); + if (unused) return NaN; + } else if ( + dep.originModule.usedExports && + importedModule && + Array.isArray(importedModule.buildMeta.providedExports) + ) { + // not sure which exports are used, but we know which are provided + + const unused = importedModule.buildMeta.providedExports.every(id => { + if (id === "default") return true; + if (dep.activeExports.has(id)) return true; + if (activeFromOtherStarExports.has(id)) return true; + return false; + }); + if (unused) return NaN; + } + } + return super.getHarmonyInitOrder(dep); + } + + getContent(dep) { + const mode = dep.getMode(false); + const module = dep.originModule; + const importedModule = dep._module; + const importVar = dep.getImportVar(); + + switch (mode.type) { + case "missing": + return `throw new Error(${JSON.stringify( + `Cannot find module '${mode.userRequest}'` + )});\n`; + + case "unused": + return `${Template.toNormalComment( + `unused harmony reexport ${mode.name}` + )}\n`; + + case "reexport-non-harmony-default": + return ( + "/* harmony reexport (default from non-harmony) */ " + + this.getReexportStatement( + module, + module.isUsed(mode.name), + importVar, + null + ) + ); + + case "reexport-named-default": + return ( + "/* harmony reexport (default from named exports) */ " + + this.getReexportStatement( + module, + module.isUsed(mode.name), + importVar, + "" + ) + ); + + case "reexport-fake-namespace-object": + return ( + "/* harmony reexport (fake namespace object from non-harmony) */ " + + this.getReexportFakeNamespaceObjectStatement( + module, + module.isUsed(mode.name), + importVar + ) + ); + + case "rexport-non-harmony-undefined": + return ( + "/* harmony reexport (non default export from non-harmony) */ " + + this.getReexportStatement( + module, + module.isUsed(mode.name), + "undefined", + "" + ) + ); + + case "reexport-non-harmony-default-strict": + return ( + "/* harmony reexport (default from non-harmony) */ " + + this.getReexportStatement( + module, + module.isUsed(mode.name), + importVar, + "" + ) + ); + + case "reexport-namespace-object": + return ( + "/* harmony reexport (module object) */ " + + this.getReexportStatement( + module, + module.isUsed(mode.name), + importVar, + "" + ) + ); + + case "empty-star": + return "/* empty/unused harmony star reexport */"; + + case "safe-reexport": + return Array.from(mode.map.entries()) + .map(item => { + return ( + "/* harmony reexport (safe) */ " + + this.getReexportStatement( + module, + module.isUsed(item[0]), + importVar, + importedModule.isUsed(item[1]) + ) + + "\n" + ); + }) + .join(""); + + case "checked-reexport": + return Array.from(mode.map.entries()) + .map(item => { + return ( + "/* harmony reexport (checked) */ " + + this.getConditionalReexportStatement( + module, + item[0], + importVar, + item[1] + ) + + "\n" + ); + }) + .join(""); + + case "dynamic-reexport": { + const activeExports = new Set([ + ...dep.activeExports, + ...dep._discoverActiveExportsFromOtherStartExports() + ]); + let content = + "/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in " + + importVar + + ") "; + + // Filter out exports which are defined by other exports + // and filter out default export because it cannot be reexported with * + if (activeExports.size > 0) { + content += + "if(" + + JSON.stringify(Array.from(activeExports).concat("default")) + + ".indexOf(__WEBPACK_IMPORT_KEY__) < 0) "; + } else { + content += "if(__WEBPACK_IMPORT_KEY__ !== 'default') "; + } + const exportsName = dep.originModule.exportsArgument; + return ( + content + + `(function(key) { __webpack_require__.d(${exportsName}, key, function() { return ${importVar}[key]; }) }(__WEBPACK_IMPORT_KEY__));\n` + ); + } + + default: + throw new Error(`Unknown mode ${mode.type}`); + } + } + + getReexportStatement(module, key, name, valueKey) { + const exportsName = module.exportsArgument; + const returnValue = this.getReturnValue(name, valueKey); + return `__webpack_require__.d(${exportsName}, ${JSON.stringify( + key + )}, function() { return ${returnValue}; });\n`; + } + + getReexportFakeNamespaceObjectStatement(module, key, name) { + const exportsName = module.exportsArgument; + return `__webpack_require__.d(${exportsName}, ${JSON.stringify( + key + )}, function() { return __webpack_require__.t(${name}); });\n`; + } + + getConditionalReexportStatement(module, key, name, valueKey) { + if (valueKey === false) { + return "/* unused export */\n"; + } + const exportsName = module.exportsArgument; + const returnValue = this.getReturnValue(name, valueKey); + return `if(__webpack_require__.o(${name}, ${JSON.stringify( + valueKey + )})) __webpack_require__.d(${exportsName}, ${JSON.stringify( + key + )}, function() { return ${returnValue}; });\n`; + } + + getReturnValue(name, valueKey) { + if (valueKey === null) { + return `${name}_default.a`; + } + if (valueKey === "") { + return name; + } + if (valueKey === false) { + return "/* unused export */ undefined"; + } + + return `${name}[${JSON.stringify(valueKey)}]`; + } +}; diff --git a/node_modules/webpack/lib/dependencies/HarmonyExportSpecifierDependency.js b/node_modules/webpack/lib/dependencies/HarmonyExportSpecifierDependency.js index 33c253f4b..1bf6a3fe6 100644 --- a/node_modules/webpack/lib/dependencies/HarmonyExportSpecifierDependency.js +++ b/node_modules/webpack/lib/dependencies/HarmonyExportSpecifierDependency.js @@ -1,54 +1,54 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const NullDependency = require("./NullDependency");
-
-class HarmonyExportSpecifierDependency extends NullDependency {
- constructor(originModule, id, name, position, immutable) {
- super();
- this.originModule = originModule;
- this.id = id;
- this.name = name;
- this.position = position;
- this.immutable = immutable;
- }
-
- get type() {
- return "harmony export specifier";
- }
-
- getExports() {
- return {
- exports: [this.name]
- };
- }
-}
-
-HarmonyExportSpecifierDependency.Template = class HarmonyExportSpecifierDependencyTemplate {
- apply(dep, source) {
- const content = this.getPrefix(dep) + this.getContent(dep);
- source.insert(dep.position, content);
- }
-
- getPrefix(dep) {
- return dep.position > 0 ? "\n" : "";
- }
-
- getContent(dep) {
- const used = dep.originModule.isUsed(dep.name);
- if(!used) {
- return `/* unused harmony export ${(dep.name || "namespace")} */\n`;
- }
-
- const exportsName = dep.originModule.exportsArgument || "exports";
- if(dep.immutable) {
- return `/* harmony export (immutable) */ ${exportsName}[${JSON.stringify(used)}] = ${dep.id};\n`;
- }
-
- return `/* harmony export (binding) */ __webpack_require__.d(${exportsName}, ${JSON.stringify(used)}, function() { return ${dep.id}; });\n`;
- }
-};
-
-module.exports = HarmonyExportSpecifierDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const NullDependency = require("./NullDependency"); + +class HarmonyExportSpecifierDependency extends NullDependency { + constructor(originModule, id, name) { + super(); + this.originModule = originModule; + this.id = id; + this.name = name; + } + + get type() { + return "harmony export specifier"; + } + + getExports() { + return { + exports: [this.name], + dependencies: undefined + }; + } +} + +HarmonyExportSpecifierDependency.Template = class HarmonyExportSpecifierDependencyTemplate { + apply(dep, source) {} + + getHarmonyInitOrder(dep) { + return 0; + } + + harmonyInit(dep, source, runtime) { + const content = this.getContent(dep); + source.insert(-1, content); + } + + getContent(dep) { + const used = dep.originModule.isUsed(dep.name); + if (!used) { + return `/* unused harmony export ${dep.name || "namespace"} */\n`; + } + + const exportsName = dep.originModule.exportsArgument; + + return `/* harmony export (binding) */ __webpack_require__.d(${exportsName}, ${JSON.stringify( + used + )}, function() { return ${dep.id}; });\n`; + } +}; + +module.exports = HarmonyExportSpecifierDependency; diff --git a/node_modules/webpack/lib/dependencies/HarmonyImportDependency.js b/node_modules/webpack/lib/dependencies/HarmonyImportDependency.js index d31ef2dc8..97fd9bf6c 100644 --- a/node_modules/webpack/lib/dependencies/HarmonyImportDependency.js +++ b/node_modules/webpack/lib/dependencies/HarmonyImportDependency.js @@ -1,72 +1,109 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const ModuleDependency = require("./ModuleDependency");
-
-class HarmonyImportDependency extends ModuleDependency {
- constructor(request, importedVar, range) {
- super(request);
- this.range = range;
- this.importedVar = importedVar;
- }
-
- get type() {
- return "harmony import";
- }
-
- getReference() {
- if(!this.module) return null;
-
- return {
- module: this.module,
- importedNames: false
- };
- }
-
- updateHash(hash) {
- super.updateHash(hash);
- hash.update((this.module && (!this.module.meta || this.module.meta.harmonyModule)) + "");
- }
-}
-
-HarmonyImportDependency.Template = class HarmonyImportDependencyTemplate {
- apply(dep, source, outputOptions, requestShortener) {
- const content = makeImportStatement(true, dep, outputOptions, requestShortener);
- source.replace(dep.range[0], dep.range[1] - 1, "");
- source.insert(-1, content);
- }
-};
-
-function getOptionalComment(pathinfo, shortenedRequest) {
- if(!pathinfo) {
- return "";
- }
- return `/*! ${shortenedRequest} */ `;
-}
-
-function makeImportStatement(declare, dep, outputOptions, requestShortener) {
- const comment = getOptionalComment(outputOptions.pathinfo, requestShortener.shorten(dep.request));
- const declaration = declare ? "var " : "";
- const newline = declare ? "\n" : " ";
-
- if(!dep.module) {
- const stringifiedError = JSON.stringify(`Cannot find module "${dep.request}"`);
- return `throw new Error(${stringifiedError});${newline}`;
- }
-
- if(dep.importedVar) {
- const isHarmonyModule = dep.module.meta && dep.module.meta.harmonyModule;
- const content = `/* harmony import */ ${declaration}${dep.importedVar} = __webpack_require__(${comment}${JSON.stringify(dep.module.id)});${newline}`;
- if(isHarmonyModule) {
- return content;
- }
- return `${content}/* harmony import */ ${declaration}${dep.importedVar}_default = __webpack_require__.n(${dep.importedVar});${newline}`;
- }
-
- return "";
-}
-HarmonyImportDependency.makeImportStatement = makeImportStatement;
-
-module.exports = HarmonyImportDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const DependencyReference = require("./DependencyReference"); +const ModuleDependency = require("./ModuleDependency"); +const Template = require("../Template"); + +class HarmonyImportDependency extends ModuleDependency { + constructor(request, originModule, sourceOrder, parserScope) { + super(request); + this.redirectedModule = undefined; + this.originModule = originModule; + this.sourceOrder = sourceOrder; + this.parserScope = parserScope; + } + + get _module() { + return this.redirectedModule || this.module; + } + + getReference() { + if (!this._module) return null; + return new DependencyReference( + this._module, + false, + this.weak, + this.sourceOrder + ); + } + + getImportVar() { + let importVarMap = this.parserScope.importVarMap; + if (!importVarMap) this.parserScope.importVarMap = importVarMap = new Map(); + let importVar = importVarMap.get(this._module); + if (importVar) return importVar; + importVar = `${Template.toIdentifier( + `${this.userRequest}` + )}__WEBPACK_IMPORTED_MODULE_${importVarMap.size}__`; + importVarMap.set(this._module, importVar); + return importVar; + } + + getImportStatement(update, runtime) { + return runtime.importStatement({ + update, + module: this._module, + importVar: this.getImportVar(), + request: this.request, + originModule: this.originModule + }); + } + + updateHash(hash) { + super.updateHash(hash); + const importedModule = this._module; + hash.update( + (importedModule && + (!importedModule.buildMeta || importedModule.buildMeta.exportsType)) + + "" + ); + hash.update((importedModule && importedModule.id) + ""); + } + + disconnect() { + super.disconnect(); + this.redirectedModule = undefined; + } +} + +module.exports = HarmonyImportDependency; + +const importEmittedMap = new WeakMap(); + +HarmonyImportDependency.Template = class HarmonyImportDependencyTemplate { + apply(dep, source, runtime) { + // no-op + } + + getHarmonyInitOrder(dep) { + return dep.sourceOrder; + } + + static isImportEmitted(dep, source) { + let sourceInfo = importEmittedMap.get(source); + if (!sourceInfo) return false; + const key = dep._module || dep.request; + return key && sourceInfo.emittedImports.get(key); + } + + harmonyInit(dep, source, runtime, dependencyTemplates) { + let sourceInfo = importEmittedMap.get(source); + if (!sourceInfo) { + importEmittedMap.set( + source, + (sourceInfo = { + emittedImports: new Map() + }) + ); + } + const key = dep._module || dep.request; + if (key && sourceInfo.emittedImports.get(key)) return; + sourceInfo.emittedImports.set(key, true); + const content = dep.getImportStatement(false, runtime); + source.insert(-1, content); + } +}; diff --git a/node_modules/webpack/lib/dependencies/HarmonyImportDependencyParserPlugin.js b/node_modules/webpack/lib/dependencies/HarmonyImportDependencyParserPlugin.js index 3b867f616..7f9fcde20 100644 --- a/node_modules/webpack/lib/dependencies/HarmonyImportDependencyParserPlugin.js +++ b/node_modules/webpack/lib/dependencies/HarmonyImportDependencyParserPlugin.js @@ -1,124 +1,222 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const HarmonyImportDependency = require("./HarmonyImportDependency");
-const HarmonyImportSpecifierDependency = require("./HarmonyImportSpecifierDependency");
-const HarmonyAcceptImportDependency = require("./HarmonyAcceptImportDependency");
-const HarmonyAcceptDependency = require("./HarmonyAcceptDependency");
-const HarmonyModulesHelpers = require("./HarmonyModulesHelpers");
-
-module.exports = class HarmonyImportDependencyParserPlugin {
- constructor(moduleOptions) {
- this.strictExportPresence = moduleOptions.strictExportPresence;
- this.strictThisContextOnImports = moduleOptions.strictThisContextOnImports;
- }
-
- apply(parser) {
- parser.plugin("import", (statement, source) => {
- const dep = new HarmonyImportDependency(source, HarmonyModulesHelpers.getNewModuleVar(parser.state, source), statement.range);
- dep.loc = statement.loc;
- parser.state.current.addDependency(dep);
- parser.state.lastHarmonyImport = dep;
- return true;
- });
- parser.plugin("import specifier", (statement, source, id, name) => {
- parser.scope.definitions.length--;
- parser.scope.renames[`$${name}`] = "imported var";
- if(!parser.state.harmonySpecifier) parser.state.harmonySpecifier = {};
- parser.state.harmonySpecifier[`$${name}`] = [parser.state.lastHarmonyImport, HarmonyModulesHelpers.getModuleVar(parser.state, source), id];
- return true;
- });
- parser.plugin("expression imported var", (expr) => {
- const name = expr.name;
- const settings = parser.state.harmonySpecifier[`$${name}`];
- const dep = new HarmonyImportSpecifierDependency(settings[0], settings[1], settings[2], name, expr.range, this.strictExportPresence);
- dep.shorthand = parser.scope.inShorthand;
- dep.directImport = true;
- dep.loc = expr.loc;
- parser.state.current.addDependency(dep);
- return true;
- });
- parser.plugin("expression imported var.*", (expr) => {
- const name = expr.object.name;
- const settings = parser.state.harmonySpecifier[`$${name}`];
- if(settings[2] !== null)
- return false;
- const dep = new HarmonyImportSpecifierDependency(settings[0], settings[1], expr.property.name || expr.property.value, name, expr.range, this.strictExportPresence);
- dep.shorthand = parser.scope.inShorthand;
- dep.directImport = false;
- dep.loc = expr.loc;
- parser.state.current.addDependency(dep);
- return true;
- });
- if(this.strictThisContextOnImports) {
- // only in case when we strictly follow the spec we need a special case here
- parser.plugin("call imported var.*", (expr) => {
- if(expr.callee.type !== "MemberExpression") return;
- if(expr.callee.object.type !== "Identifier") return;
- const name = expr.callee.object.name;
- const settings = parser.state.harmonySpecifier[`$${name}`];
- if(settings[2] !== null)
- return false;
- const dep = new HarmonyImportSpecifierDependency(settings[0], settings[1], expr.callee.property.name || expr.callee.property.value, name, expr.callee.range, this.strictExportPresence);
- dep.shorthand = parser.scope.inShorthand;
- dep.directImport = false;
- dep.namespaceObjectAsContext = true;
- dep.loc = expr.callee.loc;
- parser.state.current.addDependency(dep);
- if(expr.arguments)
- parser.walkExpressions(expr.arguments);
- return true;
- });
- }
- parser.plugin("call imported var", (expr) => {
- const args = expr.arguments;
- const fullExpr = expr;
- expr = expr.callee;
- if(expr.type !== "Identifier") return;
- const name = expr.name;
- const settings = parser.state.harmonySpecifier[`$${name}`];
- const dep = new HarmonyImportSpecifierDependency(settings[0], settings[1], settings[2], name, expr.range, this.strictExportPresence);
- dep.directImport = true;
- dep.callArgs = args;
- dep.call = fullExpr;
- dep.loc = expr.loc;
- parser.state.current.addDependency(dep);
- if(args)
- parser.walkExpressions(args);
- return true;
- });
- parser.plugin("hot accept callback", (expr, requests) => {
- const dependencies = requests
- .filter(request => HarmonyModulesHelpers.checkModuleVar(parser.state, request))
- .map(request => {
- const dep = new HarmonyAcceptImportDependency(request, HarmonyModulesHelpers.getModuleVar(parser.state, request), expr.range);
- dep.loc = expr.loc;
- parser.state.current.addDependency(dep);
- return dep;
- });
- if(dependencies.length > 0) {
- const dep = new HarmonyAcceptDependency(expr.range, dependencies, true);
- dep.loc = expr.loc;
- parser.state.current.addDependency(dep);
- }
- });
- parser.plugin("hot accept without callback", (expr, requests) => {
- const dependencies = requests
- .filter(request => HarmonyModulesHelpers.checkModuleVar(parser.state, request))
- .map(request => {
- const dep = new HarmonyAcceptImportDependency(request, HarmonyModulesHelpers.getModuleVar(parser.state, request), expr.range);
- dep.loc = expr.loc;
- parser.state.current.addDependency(dep);
- return dep;
- });
- if(dependencies.length > 0) {
- const dep = new HarmonyAcceptDependency(expr.range, dependencies, false);
- dep.loc = expr.loc;
- parser.state.current.addDependency(dep);
- }
- });
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const { SyncBailHook } = require("tapable"); +const HarmonyImportSideEffectDependency = require("./HarmonyImportSideEffectDependency"); +const HarmonyImportSpecifierDependency = require("./HarmonyImportSpecifierDependency"); +const HarmonyAcceptImportDependency = require("./HarmonyAcceptImportDependency"); +const HarmonyAcceptDependency = require("./HarmonyAcceptDependency"); +const ConstDependency = require("./ConstDependency"); + +module.exports = class HarmonyImportDependencyParserPlugin { + constructor(moduleOptions) { + this.strictExportPresence = moduleOptions.strictExportPresence; + this.strictThisContextOnImports = moduleOptions.strictThisContextOnImports; + } + + apply(parser) { + parser.hooks.import.tap( + "HarmonyImportDependencyParserPlugin", + (statement, source) => { + parser.state.lastHarmonyImportOrder = + (parser.state.lastHarmonyImportOrder || 0) + 1; + const clearDep = new ConstDependency("", statement.range); + clearDep.loc = statement.loc; + parser.state.module.addDependency(clearDep); + const sideEffectDep = new HarmonyImportSideEffectDependency( + source, + parser.state.module, + parser.state.lastHarmonyImportOrder, + parser.state.harmonyParserScope + ); + sideEffectDep.loc = statement.loc; + parser.state.module.addDependency(sideEffectDep); + return true; + } + ); + parser.hooks.importSpecifier.tap( + "HarmonyImportDependencyParserPlugin", + (statement, source, id, name) => { + parser.scope.definitions.delete(name); + parser.scope.renames.set(name, "imported var"); + if (!parser.state.harmonySpecifier) { + parser.state.harmonySpecifier = new Map(); + } + parser.state.harmonySpecifier.set(name, { + source, + id, + sourceOrder: parser.state.lastHarmonyImportOrder + }); + return true; + } + ); + parser.hooks.expression + .for("imported var") + .tap("HarmonyImportDependencyParserPlugin", expr => { + const name = expr.name; + const settings = parser.state.harmonySpecifier.get(name); + const dep = new HarmonyImportSpecifierDependency( + settings.source, + parser.state.module, + settings.sourceOrder, + parser.state.harmonyParserScope, + settings.id, + name, + expr.range, + this.strictExportPresence + ); + dep.shorthand = parser.scope.inShorthand; + dep.directImport = true; + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + return true; + }); + parser.hooks.expressionAnyMember + .for("imported var") + .tap("HarmonyImportDependencyParserPlugin", expr => { + const name = expr.object.name; + const settings = parser.state.harmonySpecifier.get(name); + if (settings.id !== null) return false; + const dep = new HarmonyImportSpecifierDependency( + settings.source, + parser.state.module, + settings.sourceOrder, + parser.state.harmonyParserScope, + expr.property.name || expr.property.value, + name, + expr.range, + this.strictExportPresence + ); + dep.shorthand = parser.scope.inShorthand; + dep.directImport = false; + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + return true; + }); + if (this.strictThisContextOnImports) { + // only in case when we strictly follow the spec we need a special case here + parser.hooks.callAnyMember + .for("imported var") + .tap("HarmonyImportDependencyParserPlugin", expr => { + if (expr.callee.type !== "MemberExpression") return; + if (expr.callee.object.type !== "Identifier") return; + const name = expr.callee.object.name; + const settings = parser.state.harmonySpecifier.get(name); + if (settings.id !== null) return false; + const dep = new HarmonyImportSpecifierDependency( + settings.source, + parser.state.module, + settings.sourceOrder, + parser.state.harmonyParserScope, + expr.callee.property.name || expr.callee.property.value, + name, + expr.callee.range, + this.strictExportPresence + ); + dep.shorthand = parser.scope.inShorthand; + dep.directImport = false; + dep.namespaceObjectAsContext = true; + dep.loc = expr.callee.loc; + parser.state.module.addDependency(dep); + if (expr.arguments) parser.walkExpressions(expr.arguments); + return true; + }); + } + parser.hooks.call + .for("imported var") + .tap("HarmonyImportDependencyParserPlugin", expr => { + const args = expr.arguments; + const fullExpr = expr; + expr = expr.callee; + if (expr.type !== "Identifier") return; + const name = expr.name; + const settings = parser.state.harmonySpecifier.get(name); + const dep = new HarmonyImportSpecifierDependency( + settings.source, + parser.state.module, + settings.sourceOrder, + parser.state.harmonyParserScope, + settings.id, + name, + expr.range, + this.strictExportPresence + ); + dep.directImport = true; + dep.callArgs = args; + dep.call = fullExpr; + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + if (args) parser.walkExpressions(args); + return true; + }); + // TODO webpack 5: refactor this, no custom hooks + if (!parser.hooks.hotAcceptCallback) { + parser.hooks.hotAcceptCallback = new SyncBailHook([ + "expression", + "requests" + ]); + } + if (!parser.hooks.hotAcceptWithoutCallback) { + parser.hooks.hotAcceptWithoutCallback = new SyncBailHook([ + "expression", + "requests" + ]); + } + parser.hooks.hotAcceptCallback.tap( + "HarmonyImportDependencyParserPlugin", + (expr, requests) => { + const harmonyParserScope = parser.state.harmonyParserScope; + if (!harmonyParserScope) { + // This is not a harmony module, skip it + return; + } + const dependencies = requests.map(request => { + const dep = new HarmonyAcceptImportDependency( + request, + parser.state.module, + harmonyParserScope + ); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + return dep; + }); + if (dependencies.length > 0) { + const dep = new HarmonyAcceptDependency( + expr.range, + dependencies, + true + ); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + } + } + ); + parser.hooks.hotAcceptWithoutCallback.tap( + "HarmonyImportDependencyParserPlugin", + (expr, requests) => { + const dependencies = requests.map(request => { + const dep = new HarmonyAcceptImportDependency( + request, + parser.state.module, + parser.state.harmonyParserScope + ); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + return dep; + }); + if (dependencies.length > 0) { + const dep = new HarmonyAcceptDependency( + expr.range, + dependencies, + false + ); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + } + } + ); + } +}; diff --git a/node_modules/webpack/lib/dependencies/HarmonyImportSpecifierDependency.js b/node_modules/webpack/lib/dependencies/HarmonyImportSpecifierDependency.js index 083019291..769711932 100644 --- a/node_modules/webpack/lib/dependencies/HarmonyImportSpecifierDependency.js +++ b/node_modules/webpack/lib/dependencies/HarmonyImportSpecifierDependency.js @@ -1,129 +1,167 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const NullDependency = require("./NullDependency");
-
-class HarmonyImportSpecifierDependency extends NullDependency {
- constructor(importDependency, importedVar, id, name, range, strictExportPresence) {
- super();
- this.importDependency = importDependency;
- this.importedVar = importedVar;
- this.id = id;
- this.name = name;
- this.range = range;
- this.strictExportPresence = strictExportPresence;
- this.namespaceObjectAsContext = false;
- this.callArgs = undefined;
- this.call = undefined;
- this.directImport = undefined;
- }
-
- get type() {
- return "harmony import specifier";
- }
-
- getReference() {
- if(!this.importDependency.module) return null;
- return {
- module: this.importDependency.module,
- importedNames: this.id && !this.namespaceObjectAsContext ? [this.id] : true
- };
- }
-
- getWarnings() {
- if(this.strictExportPresence) {
- return [];
- }
- return this._getErrors();
- }
-
- getErrors() {
- if(this.strictExportPresence) {
- return this._getErrors();
- }
- return [];
- }
-
- _getErrors() {
- const importedModule = this.importDependency.module;
- if(!importedModule || !importedModule.meta || !importedModule.meta.harmonyModule) {
- return;
- }
-
- if(!this.id) {
- return;
- }
-
- if(importedModule.isProvided(this.id) !== false) {
- return;
- }
-
- const idIsNotNameMessage = this.id !== this.name ? ` (imported as '${this.name}')` : "";
- const errorMessage = `"export '${this.id}'${idIsNotNameMessage} was not found in '${this.importDependency.userRequest}'`;
- const err = new Error(errorMessage);
- err.hideStack = true;
- return [err];
- }
-
- updateHash(hash) {
- super.updateHash(hash);
- const importedModule = this.importDependency.module;
- hash.update((importedModule && importedModule.id) + "");
- hash.update((importedModule && this.id) + "");
- hash.update((importedModule && this.importedVar) + "");
- hash.update((importedModule && this.id && importedModule.isUsed(this.id)) + "");
- hash.update((importedModule && (!importedModule.meta || importedModule.meta.harmonyModule)) + "");
- hash.update((importedModule && (importedModule.used + JSON.stringify(importedModule.usedExports))) + "");
- }
-}
-
-HarmonyImportSpecifierDependency.Template = class HarmonyImportSpecifierDependencyTemplate {
- apply(dep, source) {
- const content = this.getContent(dep);
- source.replace(dep.range[0], dep.range[1] - 1, content);
- }
-
- getContent(dep) {
- const importedModule = dep.importDependency.module;
- const defaultImport = dep.directImport && dep.id === "default" && !(importedModule && (!importedModule.meta || importedModule.meta.harmonyModule));
- const shortHandPrefix = this.getShortHandPrefix(dep);
- const importedVar = dep.importedVar;
- const importedVarSuffix = this.getImportVarSuffix(dep, defaultImport, importedModule);
-
- if(dep.call && defaultImport) {
- return `${shortHandPrefix}${importedVar}_default()`;
- }
-
- if(dep.call && dep.id) {
- return `${shortHandPrefix}Object(${importedVar}${importedVarSuffix})`;
- }
-
- return `${shortHandPrefix}${importedVar}${importedVarSuffix}`;
- }
-
- getImportVarSuffix(dep, defaultImport, importedModule) {
- if(defaultImport) {
- return "_default.a";
- }
-
- if(dep.id) {
- const used = importedModule ? importedModule.isUsed(dep.id) : dep.id;
- const optionalComment = dep.id !== used ? " /* " + dep.id + " */" : "";
- return `[${JSON.stringify(used)}${optionalComment}]`;
- }
-
- return "";
- }
-
- getShortHandPrefix(dep) {
- if(!dep.shorthand) {
- return "";
- }
-
- return dep.name + ": ";
- }
-};
-
-module.exports = HarmonyImportSpecifierDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const DependencyReference = require("./DependencyReference"); +const HarmonyImportDependency = require("./HarmonyImportDependency"); +const HarmonyLinkingError = require("../HarmonyLinkingError"); + +class HarmonyImportSpecifierDependency extends HarmonyImportDependency { + constructor( + request, + originModule, + sourceOrder, + parserScope, + id, + name, + range, + strictExportPresence + ) { + super(request, originModule, sourceOrder, parserScope); + this.id = id === null ? null : `${id}`; + this.redirectedId = undefined; + this.name = name; + this.range = range; + this.strictExportPresence = strictExportPresence; + this.namespaceObjectAsContext = false; + this.callArgs = undefined; + this.call = undefined; + this.directImport = undefined; + this.shorthand = undefined; + } + + get type() { + return "harmony import specifier"; + } + + get _id() { + return this.redirectedId || this.id; + } + + getReference() { + if (!this._module) return null; + return new DependencyReference( + this._module, + this._id && !this.namespaceObjectAsContext ? [this._id] : true, + false, + this.sourceOrder + ); + } + + getWarnings() { + if ( + this.strictExportPresence || + this.originModule.buildMeta.strictHarmonyModule + ) { + return []; + } + return this._getErrors(); + } + + getErrors() { + if ( + this.strictExportPresence || + this.originModule.buildMeta.strictHarmonyModule + ) { + return this._getErrors(); + } + return []; + } + + _getErrors() { + const importedModule = this._module; + if (!importedModule) { + return; + } + + if (!importedModule.buildMeta || !importedModule.buildMeta.exportsType) { + // It's not an harmony module + if ( + this.originModule.buildMeta.strictHarmonyModule && + this._id !== "default" + ) { + // In strict harmony modules we only support the default export + const exportName = this._id + ? `the named export '${this._id}'` + : "the namespace object"; + return [ + new HarmonyLinkingError( + `Can't import ${exportName} from non EcmaScript module (only default export is available)` + ) + ]; + } + return; + } + + if (!this._id) { + return; + } + + if (importedModule.isProvided(this._id) !== false) { + // It's provided or we are not sure + return; + } + + // We are sure that it's not provided + const idIsNotNameMessage = + this._id !== this.name ? ` (imported as '${this.name}')` : ""; + const errorMessage = `"export '${ + this._id + }'${idIsNotNameMessage} was not found in '${this.userRequest}'`; + return [new HarmonyLinkingError(errorMessage)]; + } + + // implement this method to allow the occurrence order plugin to count correctly + getNumberOfIdOccurrences() { + return 0; + } + + updateHash(hash) { + super.updateHash(hash); + const importedModule = this._module; + hash.update((importedModule && this._id) + ""); + hash.update( + (importedModule && this._id && importedModule.isUsed(this._id)) + "" + ); + hash.update( + (importedModule && + (!importedModule.buildMeta || importedModule.buildMeta.exportsType)) + + "" + ); + hash.update( + (importedModule && + importedModule.used + JSON.stringify(importedModule.usedExports)) + "" + ); + } + + disconnect() { + super.disconnect(); + this.redirectedId = undefined; + } +} + +HarmonyImportSpecifierDependency.Template = class HarmonyImportSpecifierDependencyTemplate extends HarmonyImportDependency.Template { + apply(dep, source, runtime) { + super.apply(dep, source, runtime); + const content = this.getContent(dep, runtime); + source.replace(dep.range[0], dep.range[1] - 1, content); + } + + getContent(dep, runtime) { + const exportExpr = runtime.exportFromImport({ + module: dep._module, + request: dep.request, + exportName: dep._id, + originModule: dep.originModule, + asiSafe: dep.shorthand, + isCall: dep.call, + callContext: !dep.directImport, + importVar: dep.getImportVar() + }); + return dep.shorthand ? `${dep.name}: ${exportExpr}` : exportExpr; + } +}; + +module.exports = HarmonyImportSpecifierDependency; diff --git a/node_modules/webpack/lib/dependencies/HarmonyModulesHelpers.js b/node_modules/webpack/lib/dependencies/HarmonyModulesHelpers.js deleted file mode 100644 index 10ee7e27e..000000000 --- a/node_modules/webpack/lib/dependencies/HarmonyModulesHelpers.js +++ /dev/null @@ -1,32 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-class HarmonyModulesHelpers {
-
- static getModuleVar(state, request) {
- if(!state.harmonyModules) state.harmonyModules = [];
- let idx = state.harmonyModules.indexOf(request);
- if(idx < 0) {
- idx = state.harmonyModules.length;
- state.harmonyModules.push(request);
- }
- return `__WEBPACK_IMPORTED_MODULE_${idx}_${request.replace(/[^A-Za-z0-9_]/g, "_").replace(/__+/g, "_")}__`;
- }
-
- static getNewModuleVar(state, request) {
- if(state.harmonyModules && state.harmonyModules.indexOf(request) >= 0)
- return null;
- return this.getModuleVar(state, request);
- }
-
- static checkModuleVar(state, request) {
- if(!state.harmonyModules || state.harmonyModules.indexOf(request) < 0)
- return null;
- return this.getModuleVar(state, request);
- }
-}
-
-module.exports = HarmonyModulesHelpers;
diff --git a/node_modules/webpack/lib/dependencies/HarmonyModulesPlugin.js b/node_modules/webpack/lib/dependencies/HarmonyModulesPlugin.js index 896d8a2bb..43a8d4c0c 100644 --- a/node_modules/webpack/lib/dependencies/HarmonyModulesPlugin.js +++ b/node_modules/webpack/lib/dependencies/HarmonyModulesPlugin.js @@ -1,72 +1,143 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const HarmonyImportDependency = require("./HarmonyImportDependency");
-const HarmonyImportSpecifierDependency = require("./HarmonyImportSpecifierDependency");
-const HarmonyCompatiblilityDependency = require("./HarmonyCompatibilityDependency");
-const HarmonyExportHeaderDependency = require("./HarmonyExportHeaderDependency");
-const HarmonyExportExpressionDependency = require("./HarmonyExportExpressionDependency");
-const HarmonyExportSpecifierDependency = require("./HarmonyExportSpecifierDependency");
-const HarmonyExportImportedSpecifierDependency = require("./HarmonyExportImportedSpecifierDependency");
-const HarmonyAcceptDependency = require("./HarmonyAcceptDependency");
-const HarmonyAcceptImportDependency = require("./HarmonyAcceptImportDependency");
-
-const NullFactory = require("../NullFactory");
-
-const HarmonyDetectionParserPlugin = require("./HarmonyDetectionParserPlugin");
-const HarmonyImportDependencyParserPlugin = require("./HarmonyImportDependencyParserPlugin");
-const HarmonyExportDependencyParserPlugin = require("./HarmonyExportDependencyParserPlugin");
-
-class HarmonyModulesPlugin {
- constructor(options) {
- this.options = options;
- }
-
- apply(compiler) {
- compiler.plugin("compilation", (compilation, params) => {
- const normalModuleFactory = params.normalModuleFactory;
-
- compilation.dependencyFactories.set(HarmonyImportDependency, normalModuleFactory);
- compilation.dependencyTemplates.set(HarmonyImportDependency, new HarmonyImportDependency.Template());
-
- compilation.dependencyFactories.set(HarmonyImportSpecifierDependency, new NullFactory());
- compilation.dependencyTemplates.set(HarmonyImportSpecifierDependency, new HarmonyImportSpecifierDependency.Template());
-
- compilation.dependencyFactories.set(HarmonyCompatiblilityDependency, new NullFactory());
- compilation.dependencyTemplates.set(HarmonyCompatiblilityDependency, new HarmonyCompatiblilityDependency.Template());
-
- compilation.dependencyFactories.set(HarmonyExportHeaderDependency, new NullFactory());
- compilation.dependencyTemplates.set(HarmonyExportHeaderDependency, new HarmonyExportHeaderDependency.Template());
-
- compilation.dependencyFactories.set(HarmonyExportExpressionDependency, new NullFactory());
- compilation.dependencyTemplates.set(HarmonyExportExpressionDependency, new HarmonyExportExpressionDependency.Template());
-
- compilation.dependencyFactories.set(HarmonyExportSpecifierDependency, new NullFactory());
- compilation.dependencyTemplates.set(HarmonyExportSpecifierDependency, new HarmonyExportSpecifierDependency.Template());
-
- compilation.dependencyFactories.set(HarmonyExportImportedSpecifierDependency, new NullFactory());
- compilation.dependencyTemplates.set(HarmonyExportImportedSpecifierDependency, new HarmonyExportImportedSpecifierDependency.Template());
-
- compilation.dependencyFactories.set(HarmonyAcceptDependency, new NullFactory());
- compilation.dependencyTemplates.set(HarmonyAcceptDependency, new HarmonyAcceptDependency.Template());
-
- compilation.dependencyFactories.set(HarmonyAcceptImportDependency, normalModuleFactory);
- compilation.dependencyTemplates.set(HarmonyAcceptImportDependency, new HarmonyAcceptImportDependency.Template());
-
- params.normalModuleFactory.plugin("parser", (parser, parserOptions) => {
-
- if(typeof parserOptions.harmony !== "undefined" && !parserOptions.harmony)
- return;
-
- parser.apply(
- new HarmonyDetectionParserPlugin(),
- new HarmonyImportDependencyParserPlugin(this.options),
- new HarmonyExportDependencyParserPlugin()
- );
- });
- });
- }
-}
-module.exports = HarmonyModulesPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const HarmonyCompatibilityDependency = require("./HarmonyCompatibilityDependency"); +const HarmonyInitDependency = require("./HarmonyInitDependency"); +const HarmonyImportSpecifierDependency = require("./HarmonyImportSpecifierDependency"); +const HarmonyImportSideEffectDependency = require("./HarmonyImportSideEffectDependency"); +const HarmonyExportHeaderDependency = require("./HarmonyExportHeaderDependency"); +const HarmonyExportExpressionDependency = require("./HarmonyExportExpressionDependency"); +const HarmonyExportSpecifierDependency = require("./HarmonyExportSpecifierDependency"); +const HarmonyExportImportedSpecifierDependency = require("./HarmonyExportImportedSpecifierDependency"); +const HarmonyAcceptDependency = require("./HarmonyAcceptDependency"); +const HarmonyAcceptImportDependency = require("./HarmonyAcceptImportDependency"); + +const NullFactory = require("../NullFactory"); + +const HarmonyDetectionParserPlugin = require("./HarmonyDetectionParserPlugin"); +const HarmonyImportDependencyParserPlugin = require("./HarmonyImportDependencyParserPlugin"); +const HarmonyExportDependencyParserPlugin = require("./HarmonyExportDependencyParserPlugin"); +const HarmonyTopLevelThisParserPlugin = require("./HarmonyTopLevelThisParserPlugin"); + +class HarmonyModulesPlugin { + constructor(options) { + this.options = options; + } + + apply(compiler) { + compiler.hooks.compilation.tap( + "HarmonyModulesPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + HarmonyCompatibilityDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + HarmonyCompatibilityDependency, + new HarmonyCompatibilityDependency.Template() + ); + + compilation.dependencyFactories.set( + HarmonyInitDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + HarmonyInitDependency, + new HarmonyInitDependency.Template() + ); + + compilation.dependencyFactories.set( + HarmonyImportSideEffectDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + HarmonyImportSideEffectDependency, + new HarmonyImportSideEffectDependency.Template() + ); + + compilation.dependencyFactories.set( + HarmonyImportSpecifierDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + HarmonyImportSpecifierDependency, + new HarmonyImportSpecifierDependency.Template() + ); + + compilation.dependencyFactories.set( + HarmonyExportHeaderDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + HarmonyExportHeaderDependency, + new HarmonyExportHeaderDependency.Template() + ); + + compilation.dependencyFactories.set( + HarmonyExportExpressionDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + HarmonyExportExpressionDependency, + new HarmonyExportExpressionDependency.Template() + ); + + compilation.dependencyFactories.set( + HarmonyExportSpecifierDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + HarmonyExportSpecifierDependency, + new HarmonyExportSpecifierDependency.Template() + ); + + compilation.dependencyFactories.set( + HarmonyExportImportedSpecifierDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + HarmonyExportImportedSpecifierDependency, + new HarmonyExportImportedSpecifierDependency.Template() + ); + + compilation.dependencyFactories.set( + HarmonyAcceptDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + HarmonyAcceptDependency, + new HarmonyAcceptDependency.Template() + ); + + compilation.dependencyFactories.set( + HarmonyAcceptImportDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + HarmonyAcceptImportDependency, + new HarmonyAcceptImportDependency.Template() + ); + + const handler = (parser, parserOptions) => { + if (parserOptions.harmony !== undefined && !parserOptions.harmony) + return; + + new HarmonyDetectionParserPlugin().apply(parser); + new HarmonyImportDependencyParserPlugin(this.options).apply(parser); + new HarmonyExportDependencyParserPlugin(this.options).apply(parser); + new HarmonyTopLevelThisParserPlugin().apply(parser); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("HarmonyModulesPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("HarmonyModulesPlugin", handler); + } + ); + } +} +module.exports = HarmonyModulesPlugin; diff --git a/node_modules/webpack/lib/dependencies/ImportContextDependency.js b/node_modules/webpack/lib/dependencies/ImportContextDependency.js index d7f378c5c..f25a28a15 100644 --- a/node_modules/webpack/lib/dependencies/ImportContextDependency.js +++ b/node_modules/webpack/lib/dependencies/ImportContextDependency.js @@ -1,25 +1,23 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const ContextDependency = require("./ContextDependency");
-const ContextDependencyTemplateAsRequireCall = require("./ContextDependencyTemplateAsRequireCall");
-
-class ImportContextDependency extends ContextDependency {
- constructor(request, recursive, regExp, range, valueRange, chunkName) {
- super(request, recursive, regExp);
- this.range = range;
- this.valueRange = valueRange;
- this.chunkName = chunkName;
- }
-
- get type() {
- return "import() context";
- }
-
-}
-
-ImportContextDependency.Template = ContextDependencyTemplateAsRequireCall;
-
-module.exports = ImportContextDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const ContextDependency = require("./ContextDependency"); +const ContextDependencyTemplateAsRequireCall = require("./ContextDependencyTemplateAsRequireCall"); + +class ImportContextDependency extends ContextDependency { + constructor(options, range, valueRange) { + super(options); + this.range = range; + this.valueRange = valueRange; + } + + get type() { + return `import() context ${this.options.mode}`; + } +} + +ImportContextDependency.Template = ContextDependencyTemplateAsRequireCall; + +module.exports = ImportContextDependency; diff --git a/node_modules/webpack/lib/dependencies/ImportDependenciesBlock.js b/node_modules/webpack/lib/dependencies/ImportDependenciesBlock.js index 2797276b9..61e6bb272 100644 --- a/node_modules/webpack/lib/dependencies/ImportDependenciesBlock.js +++ b/node_modules/webpack/lib/dependencies/ImportDependenciesBlock.js @@ -1,17 +1,18 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const AsyncDependenciesBlock = require("../AsyncDependenciesBlock");
-const ImportDependency = require("./ImportDependency");
-
-module.exports = class ImportDependenciesBlock extends AsyncDependenciesBlock {
- constructor(request, range, chunkName, module, loc) {
- super(chunkName, module, loc);
- this.range = range;
- const dep = new ImportDependency(request, this);
- dep.loc = loc;
- this.addDependency(dep);
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const AsyncDependenciesBlock = require("../AsyncDependenciesBlock"); +const ImportDependency = require("./ImportDependency"); + +module.exports = class ImportDependenciesBlock extends AsyncDependenciesBlock { + // TODO webpack 5 reorganize arguments + constructor(request, range, groupOptions, module, loc, originModule) { + super(groupOptions, module, loc, request); + this.range = range; + const dep = new ImportDependency(request, originModule, this); + dep.loc = loc; + this.addDependency(dep); + } +}; diff --git a/node_modules/webpack/lib/dependencies/ImportDependency.js b/node_modules/webpack/lib/dependencies/ImportDependency.js index 4c2667756..520bed218 100644 --- a/node_modules/webpack/lib/dependencies/ImportDependency.js +++ b/node_modules/webpack/lib/dependencies/ImportDependency.js @@ -1,54 +1,34 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const ModuleDependency = require("./ModuleDependency");
-const DepBlockHelpers = require("./DepBlockHelpers");
-const webpackMissingPromiseModule = require("./WebpackMissingModule").promise;
-
-class ImportDependency extends ModuleDependency {
- constructor(request, block) {
- super(request);
- this.block = block;
- }
-
- get type() {
- return "import()";
- }
-}
-
-ImportDependency.Template = class ImportDependencyTemplate {
- apply(dep, source, outputOptions, requestShortener) {
- const depBlock = dep.block;
- const promise = DepBlockHelpers.getDepBlockPromise(depBlock, outputOptions, requestShortener, "import()");
- const comment = this.getOptionalComment(outputOptions.pathinfo, requestShortener.shorten(dep.request));
-
- const content = this.getContent(promise, dep, comment);
- source.replace(depBlock.range[0], depBlock.range[1] - 1, content);
- }
-
- getOptionalComment(pathinfo, shortenedRequest) {
- if(!pathinfo) {
- return "";
- }
-
- return `/*! ${shortenedRequest} */ `;
- }
-
- getContent(promise, dep, comment) {
- if(promise && dep.module) {
- const stringifiedId = JSON.stringify(dep.module.id);
- return `${promise}.then(__webpack_require__.bind(null, ${comment}${stringifiedId}))`;
- }
-
- if(dep.module) {
- const stringifiedId = JSON.stringify(dep.module.id);
- return `new Promise(function(resolve) { resolve(__webpack_require__(${comment}${stringifiedId})); })`;
- }
-
- return webpackMissingPromiseModule(dep.request);
- }
-};
-
-module.exports = ImportDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const ModuleDependency = require("./ModuleDependency"); + +class ImportDependency extends ModuleDependency { + constructor(request, originModule, block) { + super(request); + this.originModule = originModule; + this.block = block; + } + + get type() { + return "import()"; + } +} + +ImportDependency.Template = class ImportDependencyTemplate { + apply(dep, source, runtime) { + const content = runtime.moduleNamespacePromise({ + block: dep.block, + module: dep.module, + request: dep.request, + strict: dep.originModule.buildMeta.strictHarmonyModule, + message: "import()" + }); + + source.replace(dep.block.range[0], dep.block.range[1] - 1, content); + } +}; + +module.exports = ImportDependency; diff --git a/node_modules/webpack/lib/dependencies/ImportEagerContextDependency.js b/node_modules/webpack/lib/dependencies/ImportEagerContextDependency.js deleted file mode 100644 index a4b7388bc..000000000 --- a/node_modules/webpack/lib/dependencies/ImportEagerContextDependency.js +++ /dev/null @@ -1,22 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const ImportContextDependency = require("./ImportContextDependency");
-const ContextDependencyTemplateAsRequireCall = require("./ContextDependencyTemplateAsRequireCall");
-
-class ImportEagerContextDependency extends ImportContextDependency {
- constructor(request, recursive, regExp, range, valueRange, chunkName) {
- super(request, recursive, regExp, range, valueRange, chunkName);
- this.async = "eager";
- }
-
- get type() {
- return "import() context eager";
- }
-}
-
-ImportEagerContextDependency.Template = ContextDependencyTemplateAsRequireCall;
-
-module.exports = ImportEagerContextDependency;
diff --git a/node_modules/webpack/lib/dependencies/ImportEagerDependency.js b/node_modules/webpack/lib/dependencies/ImportEagerDependency.js index 9e1c2ace1..0671d5dc0 100644 --- a/node_modules/webpack/lib/dependencies/ImportEagerDependency.js +++ b/node_modules/webpack/lib/dependencies/ImportEagerDependency.js @@ -1,46 +1,32 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const ModuleDependency = require("./ModuleDependency");
-const webpackMissingPromiseModule = require("./WebpackMissingModule").promise;
-
-class ImportEagerDependency extends ModuleDependency {
- constructor(request, range) {
- super(request);
- this.range = range;
- }
-
- get type() {
- return "import()";
- }
-}
-
-ImportEagerDependency.Template = class ImportEagerDependencyTemplate {
- apply(dep, source, outputOptions, requestShortener) {
- const comment = this.getOptionalComment(outputOptions.pathinfo, requestShortener.shorten(dep.request));
-
- const content = this.getContent(dep, comment);
- source.replace(dep.range[0], dep.range[1] - 1, content);
- }
-
- getOptionalComment(pathinfo, shortenedRequest) {
- if(!pathinfo) {
- return "";
- }
-
- return `/*! ${shortenedRequest} */ `;
- }
-
- getContent(dep, comment) {
- if(dep.module) {
- const stringifiedId = JSON.stringify(dep.module.id);
- return `new Promise(function(resolve) { resolve(__webpack_require__(${comment}${stringifiedId})); })`;
- }
-
- return webpackMissingPromiseModule(dep.request);
- }
-};
-
-module.exports = ImportEagerDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const ModuleDependency = require("./ModuleDependency"); + +class ImportEagerDependency extends ModuleDependency { + constructor(request, originModule, range) { + super(request); + this.originModule = originModule; + this.range = range; + } + + get type() { + return "import() eager"; + } +} + +ImportEagerDependency.Template = class ImportEagerDependencyTemplate { + apply(dep, source, runtime) { + const content = runtime.moduleNamespacePromise({ + module: dep.module, + request: dep.request, + strict: dep.originModule.buildMeta.strictHarmonyModule, + message: "import() eager" + }); + source.replace(dep.range[0], dep.range[1] - 1, content); + } +}; + +module.exports = ImportEagerDependency; diff --git a/node_modules/webpack/lib/dependencies/ImportLazyContextDependency.js b/node_modules/webpack/lib/dependencies/ImportLazyContextDependency.js deleted file mode 100644 index b6f9187c9..000000000 --- a/node_modules/webpack/lib/dependencies/ImportLazyContextDependency.js +++ /dev/null @@ -1,22 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const ImportContextDependency = require("./ImportContextDependency");
-const ContextDependencyTemplateAsRequireCall = require("./ContextDependencyTemplateAsRequireCall");
-
-class ImportLazyContextDependency extends ImportContextDependency {
- constructor(request, recursive, regExp, range, valueRange, chunkName) {
- super(request, recursive, regExp, range, valueRange, chunkName);
- this.async = "lazy";
- }
-
- get type() {
- return "import() context lazy";
- }
-}
-
-ImportLazyContextDependency.Template = ContextDependencyTemplateAsRequireCall;
-
-module.exports = ImportLazyContextDependency;
diff --git a/node_modules/webpack/lib/dependencies/ImportLazyOnceContextDependency.js b/node_modules/webpack/lib/dependencies/ImportLazyOnceContextDependency.js deleted file mode 100644 index 607ac3f2d..000000000 --- a/node_modules/webpack/lib/dependencies/ImportLazyOnceContextDependency.js +++ /dev/null @@ -1,22 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const ImportContextDependency = require("./ImportContextDependency");
-const ContextDependencyTemplateAsRequireCall = require("./ContextDependencyTemplateAsRequireCall");
-
-class ImportLazyOnceContextDependency extends ImportContextDependency {
- constructor(request, recursive, regExp, range, valueRange, chunkName) {
- super(request, recursive, regExp, range, valueRange, chunkName);
- this.async = "lazy-once";
- }
-
- get type() {
- return "import() context lazy-once";
- }
-}
-
-ImportLazyOnceContextDependency.Template = ContextDependencyTemplateAsRequireCall;
-
-module.exports = ImportLazyOnceContextDependency;
diff --git a/node_modules/webpack/lib/dependencies/ImportParserPlugin.js b/node_modules/webpack/lib/dependencies/ImportParserPlugin.js index a775571b2..86c6b7438 100644 --- a/node_modules/webpack/lib/dependencies/ImportParserPlugin.js +++ b/node_modules/webpack/lib/dependencies/ImportParserPlugin.js @@ -1,89 +1,263 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const ImportEagerContextDependency = require("./ImportEagerContextDependency");
-const ImportWeakDependency = require("./ImportWeakDependency");
-const ImportWeakContextDependency = require("./ImportWeakContextDependency");
-const ImportLazyOnceContextDependency = require("./ImportLazyOnceContextDependency");
-const ImportLazyContextDependency = require("./ImportLazyContextDependency");
-const ImportDependenciesBlock = require("./ImportDependenciesBlock");
-const ImportEagerDependency = require("./ImportEagerDependency");
-const ContextDependencyHelpers = require("./ContextDependencyHelpers");
-const UnsupportedFeatureWarning = require("../UnsupportedFeatureWarning");
-
-class ImportParserPlugin {
- constructor(options) {
- this.options = options;
- }
-
- apply(parser) {
- const options = this.options;
-
- parser.plugin(["call System.import", "import-call"], (expr) => {
- if(expr.arguments.length !== 1)
- throw new Error("Incorrect number of arguments provided to 'import(module: string) -> Promise'.");
-
- const param = parser.evaluateExpression(expr.arguments[0]);
-
- let chunkName = null;
- let mode = "lazy";
-
- const importOptions = parser.getCommentOptions(expr.range);
- if(importOptions) {
- if(typeof importOptions.webpackChunkName !== "undefined") {
- if(typeof importOptions.webpackChunkName !== "string")
- parser.state.module.warnings.push(new UnsupportedFeatureWarning(parser.state.module, `\`webpackChunkName\` expected a string, but received: ${importOptions.webpackChunkName}.`));
- else
- chunkName = importOptions.webpackChunkName;
- }
- if(typeof importOptions.webpackMode !== "undefined") {
- if(typeof importOptions.webpackMode !== "string")
- parser.state.module.warnings.push(new UnsupportedFeatureWarning(parser.state.module, `\`webpackMode\` expected a string, but received: ${importOptions.webpackMode}.`));
- else
- mode = importOptions.webpackMode;
- }
- }
-
- if(param.isString()) {
- if(mode !== "lazy" && mode !== "eager" && mode !== "weak") {
- parser.state.module.warnings.push(new UnsupportedFeatureWarning(parser.state.module, `\`webpackMode\` expected 'lazy', 'eager' or 'weak', but received: ${mode}.`));
- }
-
- if(mode === "eager") {
- const dep = new ImportEagerDependency(param.string, expr.range);
- parser.state.current.addDependency(dep);
- } else if(mode === "weak") {
- const dep = new ImportWeakDependency(param.string, expr.range);
- parser.state.current.addDependency(dep);
- } else {
- const depBlock = new ImportDependenciesBlock(param.string, expr.range, chunkName, parser.state.module, expr.loc);
- parser.state.current.addBlock(depBlock);
- }
- return true;
- } else {
- if(mode !== "lazy" && mode !== "lazy-once" && mode !== "eager" && mode !== "weak") {
- parser.state.module.warnings.push(new UnsupportedFeatureWarning(parser.state.module, `\`webpackMode\` expected 'lazy', 'lazy-once', 'eager' or 'weak', but received: ${mode}.`));
- }
-
- let Dep = ImportLazyContextDependency;
- if(mode === "eager") {
- Dep = ImportEagerContextDependency;
- } else if(mode === "weak") {
- Dep = ImportWeakContextDependency;
- } else if(mode === "lazy-once") {
- Dep = ImportLazyOnceContextDependency;
- }
- const dep = ContextDependencyHelpers.create(Dep, expr.range, param, expr, options, chunkName);
- if(!dep) return;
- dep.loc = expr.loc;
- dep.optional = !!parser.scope.inTry;
- parser.state.current.addDependency(dep);
- return true;
- }
- });
- }
-}
-module.exports = ImportParserPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const ImportContextDependency = require("./ImportContextDependency"); +const ImportWeakDependency = require("./ImportWeakDependency"); +const ImportDependenciesBlock = require("./ImportDependenciesBlock"); +const ImportEagerDependency = require("./ImportEagerDependency"); +const ContextDependencyHelpers = require("./ContextDependencyHelpers"); +const UnsupportedFeatureWarning = require("../UnsupportedFeatureWarning"); +const CommentCompilationWarning = require("../CommentCompilationWarning"); + +class ImportParserPlugin { + constructor(options) { + this.options = options; + } + + apply(parser) { + parser.hooks.importCall.tap("ImportParserPlugin", expr => { + if (expr.arguments.length !== 1) { + throw new Error( + "Incorrect number of arguments provided to 'import(module: string) -> Promise'." + ); + } + + const param = parser.evaluateExpression(expr.arguments[0]); + + let chunkName = null; + let mode = "lazy"; + let include = null; + let exclude = null; + const groupOptions = {}; + + const { + options: importOptions, + errors: commentErrors + } = parser.parseCommentOptions(expr.range); + + if (commentErrors) { + for (const e of commentErrors) { + const { comment } = e; + parser.state.module.warnings.push( + new CommentCompilationWarning( + `Compilation error while processing magic comment(-s): /*${ + comment.value + }*/: ${e.message}`, + parser.state.module, + comment.loc + ) + ); + } + } + + if (importOptions) { + if (importOptions.webpackIgnore !== undefined) { + if (typeof importOptions.webpackIgnore !== "boolean") { + parser.state.module.warnings.push( + new UnsupportedFeatureWarning( + parser.state.module, + `\`webpackIgnore\` expected a boolean, but received: ${ + importOptions.webpackIgnore + }.`, + expr.loc + ) + ); + } else { + // Do not instrument `import()` is `webpackIgnore` is `true` + if (importOptions.webpackIgnore) { + return false; + } + } + } + if (importOptions.webpackChunkName !== undefined) { + if (typeof importOptions.webpackChunkName !== "string") { + parser.state.module.warnings.push( + new UnsupportedFeatureWarning( + parser.state.module, + `\`webpackChunkName\` expected a string, but received: ${ + importOptions.webpackChunkName + }.`, + expr.loc + ) + ); + } else { + chunkName = importOptions.webpackChunkName; + } + } + if (importOptions.webpackMode !== undefined) { + if (typeof importOptions.webpackMode !== "string") { + parser.state.module.warnings.push( + new UnsupportedFeatureWarning( + parser.state.module, + `\`webpackMode\` expected a string, but received: ${ + importOptions.webpackMode + }.`, + expr.loc + ) + ); + } else { + mode = importOptions.webpackMode; + } + } + if (importOptions.webpackPrefetch !== undefined) { + if (importOptions.webpackPrefetch === true) { + groupOptions.prefetchOrder = 0; + } else if (typeof importOptions.webpackPrefetch === "number") { + groupOptions.prefetchOrder = importOptions.webpackPrefetch; + } else { + parser.state.module.warnings.push( + new UnsupportedFeatureWarning( + parser.state.module, + `\`webpackPrefetch\` expected true or a number, but received: ${ + importOptions.webpackPrefetch + }.`, + expr.loc + ) + ); + } + } + if (importOptions.webpackPreload !== undefined) { + if (importOptions.webpackPreload === true) { + groupOptions.preloadOrder = 0; + } else if (typeof importOptions.webpackPreload === "number") { + groupOptions.preloadOrder = importOptions.webpackPreload; + } else { + parser.state.module.warnings.push( + new UnsupportedFeatureWarning( + parser.state.module, + `\`webpackPreload\` expected true or a number, but received: ${ + importOptions.webpackPreload + }.`, + expr.loc + ) + ); + } + } + if (importOptions.webpackInclude !== undefined) { + if ( + !importOptions.webpackInclude || + importOptions.webpackInclude.constructor.name !== "RegExp" + ) { + parser.state.module.warnings.push( + new UnsupportedFeatureWarning( + parser.state.module, + `\`webpackInclude\` expected a regular expression, but received: ${ + importOptions.webpackInclude + }.`, + expr.loc + ) + ); + } else { + include = new RegExp(importOptions.webpackInclude); + } + } + if (importOptions.webpackExclude !== undefined) { + if ( + !importOptions.webpackExclude || + importOptions.webpackExclude.constructor.name !== "RegExp" + ) { + parser.state.module.warnings.push( + new UnsupportedFeatureWarning( + parser.state.module, + `\`webpackExclude\` expected a regular expression, but received: ${ + importOptions.webpackExclude + }.`, + expr.loc + ) + ); + } else { + exclude = new RegExp(importOptions.webpackExclude); + } + } + } + + if (param.isString()) { + if (mode !== "lazy" && mode !== "eager" && mode !== "weak") { + parser.state.module.warnings.push( + new UnsupportedFeatureWarning( + parser.state.module, + `\`webpackMode\` expected 'lazy', 'eager' or 'weak', but received: ${mode}.`, + expr.loc + ) + ); + } + + if (mode === "eager") { + const dep = new ImportEagerDependency( + param.string, + parser.state.module, + expr.range + ); + parser.state.current.addDependency(dep); + } else if (mode === "weak") { + const dep = new ImportWeakDependency( + param.string, + parser.state.module, + expr.range + ); + parser.state.current.addDependency(dep); + } else { + const depBlock = new ImportDependenciesBlock( + param.string, + expr.range, + Object.assign(groupOptions, { + name: chunkName + }), + parser.state.module, + expr.loc, + parser.state.module + ); + parser.state.current.addBlock(depBlock); + } + return true; + } else { + if ( + mode !== "lazy" && + mode !== "lazy-once" && + mode !== "eager" && + mode !== "weak" + ) { + parser.state.module.warnings.push( + new UnsupportedFeatureWarning( + parser.state.module, + `\`webpackMode\` expected 'lazy', 'lazy-once', 'eager' or 'weak', but received: ${mode}.`, + expr.loc + ) + ); + mode = "lazy"; + } + + if (mode === "weak") { + mode = "async-weak"; + } + const dep = ContextDependencyHelpers.create( + ImportContextDependency, + expr.range, + param, + expr, + this.options, + { + chunkName, + groupOptions, + include, + exclude, + mode, + namespaceObject: parser.state.module.buildMeta.strictHarmonyModule + ? "strict" + : true + } + ); + if (!dep) return; + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + } + }); + } +} + +module.exports = ImportParserPlugin; diff --git a/node_modules/webpack/lib/dependencies/ImportPlugin.js b/node_modules/webpack/lib/dependencies/ImportPlugin.js index 27118bbcf..164719259 100644 --- a/node_modules/webpack/lib/dependencies/ImportPlugin.js +++ b/node_modules/webpack/lib/dependencies/ImportPlugin.js @@ -1,60 +1,79 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const ImportDependency = require("./ImportDependency");
-const ImportEagerDependency = require("./ImportEagerDependency");
-const ImportWeakDependency = require("./ImportWeakDependency");
-const ImportEagerContextDependency = require("./ImportEagerContextDependency");
-const ImportWeakContextDependency = require("./ImportWeakContextDependency");
-const ImportLazyOnceContextDependency = require("./ImportLazyOnceContextDependency");
-const ImportLazyContextDependency = require("./ImportLazyContextDependency");
-const ImportParserPlugin = require("./ImportParserPlugin");
-
-class ImportPlugin {
- constructor(options) {
- this.options = options;
- }
-
- apply(compiler) {
- const options = this.options;
- compiler.plugin("compilation", (compilation, params) => {
- const normalModuleFactory = params.normalModuleFactory;
- const contextModuleFactory = params.contextModuleFactory;
-
- compilation.dependencyFactories.set(ImportDependency, normalModuleFactory);
- compilation.dependencyTemplates.set(ImportDependency, new ImportDependency.Template());
-
- compilation.dependencyFactories.set(ImportEagerDependency, normalModuleFactory);
- compilation.dependencyTemplates.set(ImportEagerDependency, new ImportEagerDependency.Template());
-
- compilation.dependencyFactories.set(ImportWeakDependency, normalModuleFactory);
- compilation.dependencyTemplates.set(ImportWeakDependency, new ImportWeakDependency.Template());
-
- compilation.dependencyFactories.set(ImportEagerContextDependency, contextModuleFactory);
- compilation.dependencyTemplates.set(ImportEagerContextDependency, new ImportEagerContextDependency.Template());
-
- compilation.dependencyFactories.set(ImportWeakContextDependency, contextModuleFactory);
- compilation.dependencyTemplates.set(ImportWeakContextDependency, new ImportWeakContextDependency.Template());
-
- compilation.dependencyFactories.set(ImportLazyOnceContextDependency, contextModuleFactory);
- compilation.dependencyTemplates.set(ImportLazyOnceContextDependency, new ImportLazyOnceContextDependency.Template());
-
- compilation.dependencyFactories.set(ImportLazyContextDependency, contextModuleFactory);
- compilation.dependencyTemplates.set(ImportLazyContextDependency, new ImportLazyContextDependency.Template());
-
- normalModuleFactory.plugin("parser", (parser, parserOptions) => {
-
- if(typeof parserOptions.import !== "undefined" && !parserOptions.import)
- return;
-
- parser.apply(
- new ImportParserPlugin(options)
- );
- });
- });
- }
-}
-module.exports = ImportPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const ImportDependency = require("./ImportDependency"); +const ImportEagerDependency = require("./ImportEagerDependency"); +const ImportWeakDependency = require("./ImportWeakDependency"); +const ImportContextDependency = require("./ImportContextDependency"); +const ImportParserPlugin = require("./ImportParserPlugin"); + +class ImportPlugin { + constructor(options) { + this.options = options; + } + + apply(compiler) { + const options = this.options; + compiler.hooks.compilation.tap( + "ImportPlugin", + (compilation, { contextModuleFactory, normalModuleFactory }) => { + compilation.dependencyFactories.set( + ImportDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + ImportDependency, + new ImportDependency.Template() + ); + + compilation.dependencyFactories.set( + ImportEagerDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + ImportEagerDependency, + new ImportEagerDependency.Template() + ); + + compilation.dependencyFactories.set( + ImportWeakDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + ImportWeakDependency, + new ImportWeakDependency.Template() + ); + + compilation.dependencyFactories.set( + ImportContextDependency, + contextModuleFactory + ); + compilation.dependencyTemplates.set( + ImportContextDependency, + new ImportContextDependency.Template() + ); + + const handler = (parser, parserOptions) => { + if (parserOptions.import !== undefined && !parserOptions.import) + return; + + new ImportParserPlugin(options).apply(parser); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("ImportPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("ImportPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("ImportPlugin", handler); + } + ); + } +} +module.exports = ImportPlugin; diff --git a/node_modules/webpack/lib/dependencies/ImportWeakContextDependency.js b/node_modules/webpack/lib/dependencies/ImportWeakContextDependency.js deleted file mode 100644 index f6c19613e..000000000 --- a/node_modules/webpack/lib/dependencies/ImportWeakContextDependency.js +++ /dev/null @@ -1,22 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const ImportContextDependency = require("./ImportContextDependency");
-const ContextDependencyTemplateAsRequireCall = require("./ContextDependencyTemplateAsRequireCall");
-
-class ImportWeakContextDependency extends ImportContextDependency {
- constructor(request, recursive, regExp, range, valueRange, chunkName) {
- super(request, recursive, regExp, range, valueRange, chunkName);
- this.async = "async-weak";
- }
-
- get type() {
- return "import() context weak";
- }
-}
-
-ImportWeakContextDependency.Template = ContextDependencyTemplateAsRequireCall;
-
-module.exports = ImportWeakContextDependency;
diff --git a/node_modules/webpack/lib/dependencies/ImportWeakDependency.js b/node_modules/webpack/lib/dependencies/ImportWeakDependency.js index ccad2d92c..d48400001 100644 --- a/node_modules/webpack/lib/dependencies/ImportWeakDependency.js +++ b/node_modules/webpack/lib/dependencies/ImportWeakDependency.js @@ -1,47 +1,34 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const ModuleDependency = require("./ModuleDependency");
-const webpackMissingPromiseModule = require("./WebpackMissingModule").promise;
-
-class ImportWeakDependency extends ModuleDependency {
- constructor(request, range) {
- super(request);
- this.range = range;
- this.weak = true;
- }
-
- get type() {
- return "import() weak";
- }
-}
-
-ImportWeakDependency.Template = class ImportDependencyTemplate {
- apply(dep, source, outputOptions, requestShortener) {
- const comment = this.getOptionalComment(outputOptions.pathinfo, requestShortener.shorten(dep.request));
-
- const content = this.getContent(dep, comment);
- source.replace(dep.range[0], dep.range[1] - 1, content);
- }
-
- getOptionalComment(pathinfo, shortenedRequest) {
- if(!pathinfo) {
- return "";
- }
-
- return `/*! ${shortenedRequest} */ `;
- }
-
- getContent(dep, comment) {
- if(dep.module) {
- const stringifiedId = JSON.stringify(dep.module.id);
- return `Promise.resolve(${comment}${stringifiedId}).then(function(id) { if(!__webpack_require__.m[id]) throw new Error("Module '" + id + "' is not available (weak dependency)"); return __webpack_require__(id); })`;
- }
-
- return webpackMissingPromiseModule(dep.request);
- }
-};
-
-module.exports = ImportWeakDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const ModuleDependency = require("./ModuleDependency"); + +class ImportWeakDependency extends ModuleDependency { + constructor(request, originModule, range) { + super(request); + this.originModule = originModule; + this.range = range; + this.weak = true; + } + + get type() { + return "import() weak"; + } +} + +ImportWeakDependency.Template = class ImportDependencyTemplate { + apply(dep, source, runtime) { + const content = runtime.moduleNamespacePromise({ + module: dep.module, + request: dep.request, + strict: dep.originModule.buildMeta.strictHarmonyModule, + message: "import() weak", + weak: true + }); + source.replace(dep.range[0], dep.range[1] - 1, content); + } +}; + +module.exports = ImportWeakDependency; diff --git a/node_modules/webpack/lib/dependencies/LoaderDependency.js b/node_modules/webpack/lib/dependencies/LoaderDependency.js index 4b5aff7c5..9d0876bce 100644 --- a/node_modules/webpack/lib/dependencies/LoaderDependency.js +++ b/node_modules/webpack/lib/dependencies/LoaderDependency.js @@ -1,18 +1,21 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const ModuleDependency = require("./ModuleDependency");
-
-class LoaderDependency extends ModuleDependency {
- constructor(request) {
- super(request);
- }
-
- get type() {
- return "loader";
- }
-}
-
-module.exports = LoaderDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const ModuleDependency = require("./ModuleDependency"); + +class LoaderDependency extends ModuleDependency { + /** + * @param {string} request request string + */ + constructor(request) { + super(request); + } + + get type() { + return "loader"; + } +} + +module.exports = LoaderDependency; diff --git a/node_modules/webpack/lib/dependencies/LoaderPlugin.js b/node_modules/webpack/lib/dependencies/LoaderPlugin.js index a565ebbc4..c781d0636 100644 --- a/node_modules/webpack/lib/dependencies/LoaderPlugin.js +++ b/node_modules/webpack/lib/dependencies/LoaderPlugin.js @@ -1,60 +1,117 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const LoaderDependency = require("./LoaderDependency");
-
-class LoaderPlugin {
-
- apply(compiler) {
- compiler.plugin("compilation", (compilation, params) => {
- const normalModuleFactory = params.normalModuleFactory;
-
- compilation.dependencyFactories.set(LoaderDependency, normalModuleFactory);
- });
- compiler.plugin("compilation", (compilation) => {
- compilation.plugin("normal-module-loader", (loaderContext, module) => {
- loaderContext.loadModule = function loadModule(request, callback) {
- const dep = new LoaderDependency(request);
- dep.loc = request;
- compilation.addModuleDependencies(module, [
- [dep]
- ], true, "lm", false, (err) => {
- if(err) return callback(err);
-
- if(!dep.module) return callback(new Error("Cannot load the module"));
- if(dep.module.building) dep.module.building.push(next);
- else next();
-
- function next(err) {
- if(err) return callback(err);
-
- if(dep.module.error) return callback(dep.module.error);
- if(!dep.module._source) throw new Error("The module created for a LoaderDependency must have a property _source");
- let source, map;
- const moduleSource = dep.module._source;
- if(moduleSource.sourceAndMap) {
- const sourceAndMap = moduleSource.sourceAndMap();
- map = sourceAndMap.map;
- source = sourceAndMap.source;
- } else {
- map = moduleSource.map();
- source = moduleSource.source();
- }
- if(dep.module.fileDependencies) {
- dep.module.fileDependencies.forEach((dep) => loaderContext.addDependency(dep));
- }
- if(dep.module.contextDependencies) {
- dep.module.contextDependencies.forEach((dep) => loaderContext.addContextDependency(dep));
- }
- return callback(null, source, map, dep.module);
- }
- });
- };
- });
- });
- }
-}
-module.exports = LoaderPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const LoaderDependency = require("./LoaderDependency"); +const NormalModule = require("../NormalModule"); + +/** @typedef {import("../Module")} Module */ + +/** + * @callback LoadModuleCallback + * @param {Error=} err error object + * @param {string=} source source code + * @param {object=} map source map + * @param {Module=} module loaded module if successful + */ + +class LoaderPlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "LoaderPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + LoaderDependency, + normalModuleFactory + ); + } + ); + + compiler.hooks.compilation.tap("LoaderPlugin", compilation => { + compilation.hooks.normalModuleLoader.tap( + "LoaderPlugin", + (loaderContext, module) => { + /** + * @param {string} request the request string to load the module from + * @param {LoadModuleCallback} callback callback returning the loaded module or error + * @returns {void} + */ + loaderContext.loadModule = (request, callback) => { + const dep = new LoaderDependency(request); + dep.loc = { + name: request + }; + const factory = compilation.dependencyFactories.get( + dep.constructor + ); + if (factory === undefined) { + return callback( + new Error( + `No module factory available for dependency type: ${ + dep.constructor.name + }` + ) + ); + } + compilation.semaphore.release(); + compilation.addModuleDependencies( + module, + [ + { + factory, + dependencies: [dep] + } + ], + true, + "lm", + true, + err => { + compilation.semaphore.acquire(() => { + if (err) { + return callback(err); + } + if (!dep.module) { + return callback(new Error("Cannot load the module")); + } + // TODO consider removing this in webpack 5 + if (dep.module instanceof NormalModule && dep.module.error) { + return callback(dep.module.error); + } + if (!dep.module._source) { + throw new Error( + "The module created for a LoaderDependency must have a property _source" + ); + } + let source, map; + const moduleSource = dep.module._source; + if (moduleSource.sourceAndMap) { + const sourceAndMap = moduleSource.sourceAndMap(); + map = sourceAndMap.map; + source = sourceAndMap.source; + } else { + map = moduleSource.map(); + source = moduleSource.source(); + } + if (dep.module.buildInfo.fileDependencies) { + for (const d of dep.module.buildInfo.fileDependencies) { + loaderContext.addDependency(d); + } + } + if (dep.module.buildInfo.contextDependencies) { + for (const d of dep.module.buildInfo.contextDependencies) { + loaderContext.addContextDependency(d); + } + } + return callback(null, source, map, dep.module); + }); + } + ); + }; + } + ); + }); + } +} +module.exports = LoaderPlugin; diff --git a/node_modules/webpack/lib/dependencies/LocalModule.js b/node_modules/webpack/lib/dependencies/LocalModule.js index 7245828cb..06e5385fb 100644 --- a/node_modules/webpack/lib/dependencies/LocalModule.js +++ b/node_modules/webpack/lib/dependencies/LocalModule.js @@ -1,23 +1,23 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-class LocalModule {
- constructor(module, name, idx) {
- this.module = module;
- this.name = name;
- this.idx = idx;
- this.used = false;
- }
-
- flagUsed() {
- this.used = true;
- }
-
- variableName() {
- return "__WEBPACK_LOCAL_MODULE_" + this.idx + "__";
- }
-}
-module.exports = LocalModule;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +class LocalModule { + constructor(module, name, idx) { + this.module = module; + this.name = name; + this.idx = idx; + this.used = false; + } + + flagUsed() { + this.used = true; + } + + variableName() { + return "__WEBPACK_LOCAL_MODULE_" + this.idx + "__"; + } +} +module.exports = LocalModule; diff --git a/node_modules/webpack/lib/dependencies/LocalModuleDependency.js b/node_modules/webpack/lib/dependencies/LocalModuleDependency.js index 0358dca26..5d1e56bb9 100644 --- a/node_modules/webpack/lib/dependencies/LocalModuleDependency.js +++ b/node_modules/webpack/lib/dependencies/LocalModuleDependency.js @@ -1,24 +1,28 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const NullDependency = require("./NullDependency");
-
-class LocalModuleDependency extends NullDependency {
- constructor(localModule, range) {
- super();
- localModule.flagUsed();
- this.localModule = localModule;
- this.range = range;
- }
-}
-
-LocalModuleDependency.Template = class LocalModuleDependencyTemplate {
- apply(dep, source) {
- if(!dep.range) return;
- source.replace(dep.range[0], dep.range[1] - 1, dep.localModule.variableName());
- }
-};
-
-module.exports = LocalModuleDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const NullDependency = require("./NullDependency"); + +class LocalModuleDependency extends NullDependency { + constructor(localModule, range, callNew) { + super(); + localModule.flagUsed(); + this.localModule = localModule; + this.range = range; + this.callNew = callNew; + } +} + +LocalModuleDependency.Template = class LocalModuleDependencyTemplate { + apply(dep, source) { + if (!dep.range) return; + const moduleInstance = dep.callNew + ? `new (function () { return ${dep.localModule.variableName()}; })()` + : dep.localModule.variableName(); + source.replace(dep.range[0], dep.range[1] - 1, moduleInstance); + } +}; + +module.exports = LocalModuleDependency; diff --git a/node_modules/webpack/lib/dependencies/LocalModulesHelpers.js b/node_modules/webpack/lib/dependencies/LocalModulesHelpers.js index 0742f6cd4..056622704 100644 --- a/node_modules/webpack/lib/dependencies/LocalModulesHelpers.js +++ b/node_modules/webpack/lib/dependencies/LocalModulesHelpers.js @@ -1,46 +1,52 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const LocalModule = require("./LocalModule");
-const LocalModulesHelpers = exports;
-
-const lookup = (parent, mod) => {
- if(mod.charAt(0) !== ".") return mod;
-
- var path = parent.split("/"),
- segs = mod.split("/");
- path.pop();
-
- for(let i = 0; i < segs.length; i++) {
- const seg = segs[i];
- if(seg === "..") path.pop();
- else if(seg !== ".") path.push(seg);
- }
-
- return path.join("/");
-};
-
-LocalModulesHelpers.addLocalModule = (state, name) => {
- if(!state.localModules) state.localModules = [];
- const m = new LocalModule(state.module, name, state.localModules.length);
- state.localModules.push(m);
- return m;
-};
-
-LocalModulesHelpers.getLocalModule = (state, name, namedModule) => {
- if(!state.localModules) return null;
- if(namedModule) {
- // resolve dependency name relative to the defining named module
- name = lookup(namedModule, name);
- }
- for(let i = 0; i < state.localModules.length; i++) {
- if(state.localModules[i].name === name)
- return state.localModules[i];
- }
- return null;
-};
-
-module.exports = LocalModulesHelpers;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const LocalModule = require("./LocalModule"); +const LocalModulesHelpers = exports; + +const lookup = (parent, mod) => { + if (mod.charAt(0) !== ".") return mod; + + var path = parent.split("/"); + var segs = mod.split("/"); + path.pop(); + + for (let i = 0; i < segs.length; i++) { + const seg = segs[i]; + if (seg === "..") { + path.pop(); + } else if (seg !== ".") { + path.push(seg); + } + } + + return path.join("/"); +}; + +LocalModulesHelpers.addLocalModule = (state, name) => { + if (!state.localModules) { + state.localModules = []; + } + const m = new LocalModule(state.module, name, state.localModules.length); + state.localModules.push(m); + return m; +}; + +LocalModulesHelpers.getLocalModule = (state, name, namedModule) => { + if (!state.localModules) return null; + if (namedModule) { + // resolve dependency name relative to the defining named module + name = lookup(namedModule, name); + } + for (let i = 0; i < state.localModules.length; i++) { + if (state.localModules[i].name === name) { + return state.localModules[i]; + } + } + return null; +}; + +module.exports = LocalModulesHelpers; diff --git a/node_modules/webpack/lib/dependencies/ModuleDependency.js b/node_modules/webpack/lib/dependencies/ModuleDependency.js index b8cfb47bc..f325e7a98 100644 --- a/node_modules/webpack/lib/dependencies/ModuleDependency.js +++ b/node_modules/webpack/lib/dependencies/ModuleDependency.js @@ -1,23 +1,23 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const Dependency = require("../Dependency");
-
-class ModuleDependency extends Dependency {
- constructor(request) {
- super();
- this.request = request;
- this.userRequest = request;
- }
-
- isEqualResource(other) {
- if(!(other instanceof ModuleDependency))
- return false;
-
- return this.request === other.request;
- }
-}
-
-module.exports = ModuleDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const Dependency = require("../Dependency"); + +class ModuleDependency extends Dependency { + /** + * @param {string} request request path which needs resolving + */ + constructor(request) { + super(); + this.request = request; + this.userRequest = request; + } + + getResourceIdentifier() { + return `module${this.request}`; + } +} + +module.exports = ModuleDependency; diff --git a/node_modules/webpack/lib/dependencies/ModuleDependencyTemplateAsId.js b/node_modules/webpack/lib/dependencies/ModuleDependencyTemplateAsId.js index a83924819..82bc6b5d6 100644 --- a/node_modules/webpack/lib/dependencies/ModuleDependencyTemplateAsId.js +++ b/node_modules/webpack/lib/dependencies/ModuleDependencyTemplateAsId.js @@ -1,21 +1,17 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-class ModuleDependencyTemplateAsId {
-
- apply(dep, source, outputOptions, requestShortener) {
- if(!dep.range) return;
- const comment = outputOptions.pathinfo ?
- `/*! ${requestShortener.shorten(dep.request)} */ ` : "";
- let content;
- if(dep.module)
- content = comment + JSON.stringify(dep.module.id);
- else
- content = require("./WebpackMissingModule").module(dep.request);
- source.replace(dep.range[0], dep.range[1] - 1, content);
- }
-}
-module.exports = ModuleDependencyTemplateAsId;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +class ModuleDependencyTemplateAsId { + apply(dep, source, runtime) { + if (!dep.range) return; + const content = runtime.moduleId({ + module: dep.module, + request: dep.request + }); + source.replace(dep.range[0], dep.range[1] - 1, content); + } +} +module.exports = ModuleDependencyTemplateAsId; diff --git a/node_modules/webpack/lib/dependencies/ModuleDependencyTemplateAsRequireId.js b/node_modules/webpack/lib/dependencies/ModuleDependencyTemplateAsRequireId.js index 863ed3b31..db74b895f 100644 --- a/node_modules/webpack/lib/dependencies/ModuleDependencyTemplateAsRequireId.js +++ b/node_modules/webpack/lib/dependencies/ModuleDependencyTemplateAsRequireId.js @@ -1,21 +1,17 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-class ModuleDependencyTemplateAsRequireId {
-
- apply(dep, source, outputOptions, requestShortener) {
- if(!dep.range) return;
- const comment = outputOptions.pathinfo ?
- `/*! ${requestShortener.shorten(dep.request)} */ ` : "";
- let content;
- if(dep.module)
- content = `__webpack_require__(${comment}${JSON.stringify(dep.module.id)})`;
- else
- content = require("./WebpackMissingModule").module(dep.request);
- source.replace(dep.range[0], dep.range[1] - 1, content);
- }
-}
-module.exports = ModuleDependencyTemplateAsRequireId;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +class ModuleDependencyTemplateAsRequireId { + apply(dep, source, runtime) { + if (!dep.range) return; + const content = runtime.moduleExports({ + module: dep.module, + request: dep.request + }); + source.replace(dep.range[0], dep.range[1] - 1, content); + } +} +module.exports = ModuleDependencyTemplateAsRequireId; diff --git a/node_modules/webpack/lib/dependencies/ModuleHotAcceptDependency.js b/node_modules/webpack/lib/dependencies/ModuleHotAcceptDependency.js index 4297e57d8..403f7f1a0 100644 --- a/node_modules/webpack/lib/dependencies/ModuleHotAcceptDependency.js +++ b/node_modules/webpack/lib/dependencies/ModuleHotAcceptDependency.js @@ -1,23 +1,23 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const ModuleDependency = require("./ModuleDependency");
-const ModuleDependencyTemplateAsId = require("./ModuleDependencyTemplateAsId");
-
-class ModuleHotAcceptDependency extends ModuleDependency {
- constructor(request, range) {
- super(request);
- this.range = range;
- this.weak = true;
- }
-
- get type() {
- return "module.hot.accept";
- }
-}
-
-ModuleHotAcceptDependency.Template = ModuleDependencyTemplateAsId;
-
-module.exports = ModuleHotAcceptDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const ModuleDependency = require("./ModuleDependency"); +const ModuleDependencyTemplateAsId = require("./ModuleDependencyTemplateAsId"); + +class ModuleHotAcceptDependency extends ModuleDependency { + constructor(request, range) { + super(request); + this.range = range; + this.weak = true; + } + + get type() { + return "module.hot.accept"; + } +} + +ModuleHotAcceptDependency.Template = ModuleDependencyTemplateAsId; + +module.exports = ModuleHotAcceptDependency; diff --git a/node_modules/webpack/lib/dependencies/ModuleHotDeclineDependency.js b/node_modules/webpack/lib/dependencies/ModuleHotDeclineDependency.js index cab86cecb..49bf0af98 100644 --- a/node_modules/webpack/lib/dependencies/ModuleHotDeclineDependency.js +++ b/node_modules/webpack/lib/dependencies/ModuleHotDeclineDependency.js @@ -1,23 +1,23 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const ModuleDependency = require("./ModuleDependency");
-const ModuleDependencyTemplateAsId = require("./ModuleDependencyTemplateAsId");
-
-class ModuleHotDeclineDependency extends ModuleDependency {
- constructor(request, range) {
- super(request);
- this.range = range;
- this.weak = true;
- }
-
- get type() {
- return "module.hot.decline";
- }
-}
-
-ModuleHotDeclineDependency.Template = ModuleDependencyTemplateAsId;
-
-module.exports = ModuleHotDeclineDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const ModuleDependency = require("./ModuleDependency"); +const ModuleDependencyTemplateAsId = require("./ModuleDependencyTemplateAsId"); + +class ModuleHotDeclineDependency extends ModuleDependency { + constructor(request, range) { + super(request); + this.range = range; + this.weak = true; + } + + get type() { + return "module.hot.decline"; + } +} + +ModuleHotDeclineDependency.Template = ModuleDependencyTemplateAsId; + +module.exports = ModuleHotDeclineDependency; diff --git a/node_modules/webpack/lib/dependencies/MultiEntryDependency.js b/node_modules/webpack/lib/dependencies/MultiEntryDependency.js index 6196b95a5..712d3ff1f 100644 --- a/node_modules/webpack/lib/dependencies/MultiEntryDependency.js +++ b/node_modules/webpack/lib/dependencies/MultiEntryDependency.js @@ -1,20 +1,25 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const Dependency = require("../Dependency");
-
-class MultiEntryDependency extends Dependency {
- constructor(dependencies, name) {
- super();
- this.dependencies = dependencies;
- this.name = name;
- }
-
- get type() {
- return "multi entry";
- }
-}
-
-module.exports = MultiEntryDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +/** @typedef {import("./SingleEntryDependency")} SingleEntryDependency */ +const Dependency = require("../Dependency"); + +class MultiEntryDependency extends Dependency { + /** + * @param {SingleEntryDependency[]} dependencies an array of SingleEntryDependencies + * @param {string} name entry name + */ + constructor(dependencies, name) { + super(); + this.dependencies = dependencies; + this.name = name; + } + + get type() { + return "multi entry"; + } +} + +module.exports = MultiEntryDependency; diff --git a/node_modules/webpack/lib/dependencies/NullDependency.js b/node_modules/webpack/lib/dependencies/NullDependency.js index 5d389e67e..585f5fc0c 100644 --- a/node_modules/webpack/lib/dependencies/NullDependency.js +++ b/node_modules/webpack/lib/dependencies/NullDependency.js @@ -1,24 +1,20 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const Dependency = require("../Dependency");
-
-class NullDependency extends Dependency {
- get type() {
- return "null";
- }
-
- isEqualResource() {
- return false;
- }
-
- updateHash() {}
-}
-
-NullDependency.Template = class NullDependencyTemplate {
- apply() {}
-};
-
-module.exports = NullDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const Dependency = require("../Dependency"); + +class NullDependency extends Dependency { + get type() { + return "null"; + } + + updateHash() {} +} + +NullDependency.Template = class NullDependencyTemplate { + apply() {} +}; + +module.exports = NullDependency; diff --git a/node_modules/webpack/lib/dependencies/PrefetchDependency.js b/node_modules/webpack/lib/dependencies/PrefetchDependency.js index 98ca185b8..7107d83c1 100644 --- a/node_modules/webpack/lib/dependencies/PrefetchDependency.js +++ b/node_modules/webpack/lib/dependencies/PrefetchDependency.js @@ -1,18 +1,18 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const ModuleDependency = require("./ModuleDependency");
-
-class PrefetchDependency extends ModuleDependency {
- constructor(request) {
- super(request);
- }
-
- get type() {
- return "prefetch";
- }
-}
-
-module.exports = PrefetchDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const ModuleDependency = require("./ModuleDependency"); + +class PrefetchDependency extends ModuleDependency { + constructor(request) { + super(request); + } + + get type() { + return "prefetch"; + } +} + +module.exports = PrefetchDependency; diff --git a/node_modules/webpack/lib/dependencies/RequireContextDependency.js b/node_modules/webpack/lib/dependencies/RequireContextDependency.js index e37b1b54c..fd2e728fb 100644 --- a/node_modules/webpack/lib/dependencies/RequireContextDependency.js +++ b/node_modules/webpack/lib/dependencies/RequireContextDependency.js @@ -1,26 +1,22 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const ContextDependency = require("./ContextDependency");
-const ModuleDependencyTemplateAsRequireId = require("./ModuleDependencyTemplateAsRequireId");
-
-class RequireContextDependency extends ContextDependency {
- constructor(request, recursive, regExp, asyncMode, range) {
- super(request, recursive, regExp);
- this.range = range;
-
- if(asyncMode) {
- this.async = asyncMode;
- }
- }
-
- get type() {
- return "require.context";
- }
-}
-
-RequireContextDependency.Template = ModuleDependencyTemplateAsRequireId;
-
-module.exports = RequireContextDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const ContextDependency = require("./ContextDependency"); +const ModuleDependencyTemplateAsRequireId = require("./ModuleDependencyTemplateAsRequireId"); + +class RequireContextDependency extends ContextDependency { + constructor(options, range) { + super(options); + this.range = range; + } + + get type() { + return "require.context"; + } +} + +RequireContextDependency.Template = ModuleDependencyTemplateAsRequireId; + +module.exports = RequireContextDependency; diff --git a/node_modules/webpack/lib/dependencies/RequireContextDependencyParserPlugin.js b/node_modules/webpack/lib/dependencies/RequireContextDependencyParserPlugin.js index 04a8b25b9..1071fc01d 100644 --- a/node_modules/webpack/lib/dependencies/RequireContextDependencyParserPlugin.js +++ b/node_modules/webpack/lib/dependencies/RequireContextDependencyParserPlugin.js @@ -1,50 +1,56 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const RequireContextDependency = require("./RequireContextDependency");
-
-module.exports = class RequireContextDependencyParserPlugin {
- apply(parser) {
- parser.plugin("call require.context", expr => {
- let regExp = /^\.\/.*$/;
- let recursive = true;
- let asyncMode;
- switch(expr.arguments.length) {
- case 4:
- {
- const asyncModeExpr = parser.evaluateExpression(expr.arguments[3]);
- if(!asyncModeExpr.isString()) return;
- asyncMode = asyncModeExpr.string;
- }
- // falls through
- case 3:
- {
- const regExpExpr = parser.evaluateExpression(expr.arguments[2]);
- if(!regExpExpr.isRegExp()) return;
- regExp = regExpExpr.regExp;
- }
- // falls through
- case 2:
- {
- const recursiveExpr = parser.evaluateExpression(expr.arguments[1]);
- if(!recursiveExpr.isBoolean()) return;
- recursive = recursiveExpr.bool;
- }
- // falls through
- case 1:
- {
- const requestExpr = parser.evaluateExpression(expr.arguments[0]);
- if(!requestExpr.isString()) return;
- const dep = new RequireContextDependency(requestExpr.string, recursive, regExp, asyncMode, expr.range);
- dep.loc = expr.loc;
- dep.optional = parser.scope.inTry;
- parser.state.current.addDependency(dep);
- return true;
- }
- }
- });
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const RequireContextDependency = require("./RequireContextDependency"); + +module.exports = class RequireContextDependencyParserPlugin { + apply(parser) { + parser.hooks.call + .for("require.context") + .tap("RequireContextDependencyParserPlugin", expr => { + let regExp = /^\.\/.*$/; + let recursive = true; + let mode = "sync"; + switch (expr.arguments.length) { + case 4: { + const modeExpr = parser.evaluateExpression(expr.arguments[3]); + if (!modeExpr.isString()) return; + mode = modeExpr.string; + } + // falls through + case 3: { + const regExpExpr = parser.evaluateExpression(expr.arguments[2]); + if (!regExpExpr.isRegExp()) return; + regExp = regExpExpr.regExp; + } + // falls through + case 2: { + const recursiveExpr = parser.evaluateExpression(expr.arguments[1]); + if (!recursiveExpr.isBoolean()) return; + recursive = recursiveExpr.bool; + } + // falls through + case 1: { + const requestExpr = parser.evaluateExpression(expr.arguments[0]); + if (!requestExpr.isString()) return; + const dep = new RequireContextDependency( + { + request: requestExpr.string, + recursive, + regExp, + mode + }, + expr.range + ); + dep.loc = expr.loc; + dep.optional = parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + } + } + }); + } +}; diff --git a/node_modules/webpack/lib/dependencies/RequireContextPlugin.js b/node_modules/webpack/lib/dependencies/RequireContextPlugin.js index 3e08729d3..4e44e8711 100644 --- a/node_modules/webpack/lib/dependencies/RequireContextPlugin.js +++ b/node_modules/webpack/lib/dependencies/RequireContextPlugin.js @@ -1,96 +1,143 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const RequireContextDependency = require("./RequireContextDependency");
-const ContextElementDependency = require("./ContextElementDependency");
-
-const RequireContextDependencyParserPlugin = require("./RequireContextDependencyParserPlugin");
-
-class RequireContextPlugin {
- constructor(modulesDirectories, extensions, mainFiles) {
- if(!Array.isArray(modulesDirectories))
- throw new Error("modulesDirectories must be an array");
- if(!Array.isArray(extensions))
- throw new Error("extensions must be an array");
- this.modulesDirectories = modulesDirectories;
- this.extensions = extensions;
- this.mainFiles = mainFiles;
- }
-
- apply(compiler) {
- compiler.plugin("compilation", (compilation, params) => {
- const contextModuleFactory = params.contextModuleFactory;
- const normalModuleFactory = params.normalModuleFactory;
-
- compilation.dependencyFactories.set(RequireContextDependency, contextModuleFactory);
- compilation.dependencyTemplates.set(RequireContextDependency, new RequireContextDependency.Template());
-
- compilation.dependencyFactories.set(ContextElementDependency, normalModuleFactory);
-
- params.normalModuleFactory.plugin("parser", (parser, parserOptions) => {
-
- if(typeof parserOptions.requireContext !== "undefined" && !parserOptions.requireContext)
- return;
-
- parser.apply(new RequireContextDependencyParserPlugin());
- });
-
- params.contextModuleFactory.plugin("alternatives", (items, callback) => {
- if(items.length === 0) return callback(null, items);
-
- callback(null, items.map((obj) => {
- return this.extensions.filter((ext) => {
- const l = obj.request.length;
- return l > ext.length && obj.request.substr(l - ext.length, l) === ext;
- }).map((ext) => {
- const l = obj.request.length;
- return {
- context: obj.context,
- request: obj.request.substr(0, l - ext.length)
- };
- }).concat(obj);
- }).reduce((a, b) => a.concat(b), []));
- });
-
- params.contextModuleFactory.plugin("alternatives", (items, callback) => {
- if(items.length === 0) return callback(null, items);
-
- callback(null, items.map((obj) => {
- return this.mainFiles.filter((mainFile) => {
- const l = obj.request.length;
- return l > mainFile.length + 1 && obj.request.substr(l - mainFile.length - 1, l) === "/" + mainFile;
- }).map((mainFile) => {
- const l = obj.request.length;
- return [{
- context: obj.context,
- request: obj.request.substr(0, l - mainFile.length)
- }, {
- context: obj.context,
- request: obj.request.substr(0, l - mainFile.length - 1)
- }];
- }).reduce((a, b) => a.concat(b), []).concat(obj);
- }).reduce((a, b) => a.concat(b), []));
- });
-
- params.contextModuleFactory.plugin("alternatives", (items, callback) => {
- if(items.length === 0) return callback(null, items);
-
- callback(null, items.map((obj) => {
- for(let i = 0; i < this.modulesDirectories.length; i++) {
- const dir = this.modulesDirectories[i];
- const idx = obj.request.indexOf("./" + dir + "/");
- if(idx === 0) {
- obj.request = obj.request.slice(dir.length + 3);
- break;
- }
- }
- return obj;
- }));
- });
- });
- }
-}
-module.exports = RequireContextPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const RequireContextDependency = require("./RequireContextDependency"); +const ContextElementDependency = require("./ContextElementDependency"); + +const RequireContextDependencyParserPlugin = require("./RequireContextDependencyParserPlugin"); + +class RequireContextPlugin { + constructor(modulesDirectories, extensions, mainFiles) { + if (!Array.isArray(modulesDirectories)) { + throw new Error("modulesDirectories must be an array"); + } + if (!Array.isArray(extensions)) { + throw new Error("extensions must be an array"); + } + this.modulesDirectories = modulesDirectories; + this.extensions = extensions; + this.mainFiles = mainFiles; + } + + apply(compiler) { + compiler.hooks.compilation.tap( + "RequireContextPlugin", + (compilation, { contextModuleFactory, normalModuleFactory }) => { + compilation.dependencyFactories.set( + RequireContextDependency, + contextModuleFactory + ); + compilation.dependencyTemplates.set( + RequireContextDependency, + new RequireContextDependency.Template() + ); + + compilation.dependencyFactories.set( + ContextElementDependency, + normalModuleFactory + ); + + const handler = (parser, parserOptions) => { + if ( + parserOptions.requireContext !== undefined && + !parserOptions.requireContext + ) + return; + + new RequireContextDependencyParserPlugin().apply(parser); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("RequireContextPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("RequireContextPlugin", handler); + + contextModuleFactory.hooks.alternatives.tap( + "RequireContextPlugin", + items => { + if (items.length === 0) return items; + return items + .map(obj => { + return this.extensions + .filter(ext => { + const l = obj.request.length; + return ( + l > ext.length && + obj.request.substr(l - ext.length, l) === ext + ); + }) + .map(ext => { + const l = obj.request.length; + return { + context: obj.context, + request: obj.request.substr(0, l - ext.length) + }; + }) + .concat(obj); + }) + .reduce((a, b) => a.concat(b), []); + } + ); + + contextModuleFactory.hooks.alternatives.tap( + "RequireContextPlugin", + items => { + if (items.length === 0) return items; + return items + .map(obj => { + return this.mainFiles + .filter(mainFile => { + const l = obj.request.length; + return ( + l > mainFile.length + 1 && + obj.request.substr(l - mainFile.length - 1, l) === + "/" + mainFile + ); + }) + .map(mainFile => { + const l = obj.request.length; + return [ + { + context: obj.context, + request: obj.request.substr(0, l - mainFile.length) + }, + { + context: obj.context, + request: obj.request.substr(0, l - mainFile.length - 1) + } + ]; + }) + .reduce((a, b) => a.concat(b), []) + .concat(obj); + }) + .reduce((a, b) => a.concat(b), []); + } + ); + + contextModuleFactory.hooks.alternatives.tap( + "RequireContextPlugin", + items => { + if (items.length === 0) return items; + return items.map(obj => { + for (let i = 0; i < this.modulesDirectories.length; i++) { + const dir = this.modulesDirectories[i]; + const idx = obj.request.indexOf("./" + dir + "/"); + if (idx === 0) { + obj.request = obj.request.slice(dir.length + 3); + break; + } + } + return obj; + }); + } + ); + } + ); + } +} +module.exports = RequireContextPlugin; diff --git a/node_modules/webpack/lib/dependencies/RequireEnsureDependenciesBlock.js b/node_modules/webpack/lib/dependencies/RequireEnsureDependenciesBlock.js index 4d72b07ab..2a5dde704 100644 --- a/node_modules/webpack/lib/dependencies/RequireEnsureDependenciesBlock.js +++ b/node_modules/webpack/lib/dependencies/RequireEnsureDependenciesBlock.js @@ -1,22 +1,33 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const AsyncDependenciesBlock = require("../AsyncDependenciesBlock");
-const RequireEnsureDependency = require("./RequireEnsureDependency");
-
-module.exports = class RequireEnsureDependenciesBlock extends AsyncDependenciesBlock {
- constructor(expr, successExpression, errorExpression, chunkName, chunkNameRange, module, loc) {
- super(chunkName, module, loc);
- this.expr = expr;
- const successBodyRange = successExpression && successExpression.body && successExpression.body.range;
- if(successBodyRange) {
- this.range = [successBodyRange[0] + 1, successBodyRange[1] - 1];
- }
- this.chunkNameRange = chunkNameRange;
- const dep = new RequireEnsureDependency(this);
- dep.loc = loc;
- this.addDependency(dep);
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const AsyncDependenciesBlock = require("../AsyncDependenciesBlock"); +const RequireEnsureDependency = require("./RequireEnsureDependency"); + +module.exports = class RequireEnsureDependenciesBlock extends AsyncDependenciesBlock { + constructor( + expr, + successExpression, + errorExpression, + chunkName, + chunkNameRange, + module, + loc + ) { + super(chunkName, module, loc, null); + this.expr = expr; + const successBodyRange = + successExpression && + successExpression.body && + successExpression.body.range; + if (successBodyRange) { + this.range = [successBodyRange[0] + 1, successBodyRange[1] - 1]; + } + this.chunkNameRange = chunkNameRange; + const dep = new RequireEnsureDependency(this); + dep.loc = loc; + this.addDependency(dep); + } +}; diff --git a/node_modules/webpack/lib/dependencies/RequireEnsureDependenciesBlockParserPlugin.js b/node_modules/webpack/lib/dependencies/RequireEnsureDependenciesBlockParserPlugin.js index 73b7d0c8c..213eaac0a 100644 --- a/node_modules/webpack/lib/dependencies/RequireEnsureDependenciesBlockParserPlugin.js +++ b/node_modules/webpack/lib/dependencies/RequireEnsureDependenciesBlockParserPlugin.js @@ -1,102 +1,116 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const RequireEnsureDependenciesBlock = require("./RequireEnsureDependenciesBlock");
-const RequireEnsureItemDependency = require("./RequireEnsureItemDependency");
-const getFunctionExpression = require("./getFunctionExpression");
-
-module.exports = class RequireEnsureDependenciesBlockParserPlugin {
- apply(parser) {
- parser.plugin("call require.ensure", expr => {
- let chunkName = null;
- let chunkNameRange = null;
- let errorExpressionArg = null;
- let errorExpression = null;
- switch(expr.arguments.length) {
- case 4:
- {
- const chunkNameExpr = parser.evaluateExpression(expr.arguments[3]);
- if(!chunkNameExpr.isString()) return;
- chunkNameRange = chunkNameExpr.range;
- chunkName = chunkNameExpr.string;
- }
- // falls through
- case 3:
- {
- errorExpressionArg = expr.arguments[2];
- errorExpression = getFunctionExpression(errorExpressionArg);
-
- if(!errorExpression && !chunkName) {
- const chunkNameExpr = parser.evaluateExpression(expr.arguments[2]);
- if(!chunkNameExpr.isString()) return;
- chunkNameRange = chunkNameExpr.range;
- chunkName = chunkNameExpr.string;
- }
- }
- // falls through
- case 2:
- {
- const dependenciesExpr = parser.evaluateExpression(expr.arguments[0]);
- const dependenciesItems = dependenciesExpr.isArray() ? dependenciesExpr.items : [dependenciesExpr];
- const successExpressionArg = expr.arguments[1];
- const successExpression = getFunctionExpression(successExpressionArg);
-
- if(successExpression) {
- parser.walkExpressions(successExpression.expressions);
- }
- if(errorExpression) {
- parser.walkExpressions(errorExpression.expressions);
- }
-
- const dep = new RequireEnsureDependenciesBlock(expr,
- successExpression ? successExpression.fn : successExpressionArg,
- errorExpression ? errorExpression.fn : errorExpressionArg,
- chunkName, chunkNameRange, parser.state.module, expr.loc);
- const old = parser.state.current;
- parser.state.current = dep;
- try {
- let failed = false;
- parser.inScope([], () => {
- dependenciesItems.forEach(ee => {
- if(ee.isString()) {
- const edep = new RequireEnsureItemDependency(ee.string, ee.range);
- edep.loc = dep.loc;
- dep.addDependency(edep);
- } else {
- failed = true;
- }
- });
- });
- if(failed) {
- return;
- }
- if(successExpression) {
- if(successExpression.fn.body.type === "BlockStatement")
- parser.walkStatement(successExpression.fn.body);
- else
- parser.walkExpression(successExpression.fn.body);
- }
- old.addBlock(dep);
- } finally {
- parser.state.current = old;
- }
- if(!successExpression) {
- parser.walkExpression(successExpressionArg);
- }
- if(errorExpression) {
- if(errorExpression.fn.body.type === "BlockStatement")
- parser.walkStatement(errorExpression.fn.body);
- else
- parser.walkExpression(errorExpression.fn.body);
- } else if(errorExpressionArg) {
- parser.walkExpression(errorExpressionArg);
- }
- return true;
- }
- }
- });
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const RequireEnsureDependenciesBlock = require("./RequireEnsureDependenciesBlock"); +const RequireEnsureItemDependency = require("./RequireEnsureItemDependency"); +const getFunctionExpression = require("./getFunctionExpression"); + +module.exports = class RequireEnsureDependenciesBlockParserPlugin { + apply(parser) { + parser.hooks.call + .for("require.ensure") + .tap("RequireEnsureDependenciesBlockParserPlugin", expr => { + let chunkName = null; + let chunkNameRange = null; + let errorExpressionArg = null; + let errorExpression = null; + switch (expr.arguments.length) { + case 4: { + const chunkNameExpr = parser.evaluateExpression(expr.arguments[3]); + if (!chunkNameExpr.isString()) return; + chunkNameRange = chunkNameExpr.range; + chunkName = chunkNameExpr.string; + } + // falls through + case 3: { + errorExpressionArg = expr.arguments[2]; + errorExpression = getFunctionExpression(errorExpressionArg); + + if (!errorExpression && !chunkName) { + const chunkNameExpr = parser.evaluateExpression( + expr.arguments[2] + ); + if (!chunkNameExpr.isString()) return; + chunkNameRange = chunkNameExpr.range; + chunkName = chunkNameExpr.string; + } + } + // falls through + case 2: { + const dependenciesExpr = parser.evaluateExpression( + expr.arguments[0] + ); + const dependenciesItems = dependenciesExpr.isArray() + ? dependenciesExpr.items + : [dependenciesExpr]; + const successExpressionArg = expr.arguments[1]; + const successExpression = getFunctionExpression( + successExpressionArg + ); + + if (successExpression) { + parser.walkExpressions(successExpression.expressions); + } + if (errorExpression) { + parser.walkExpressions(errorExpression.expressions); + } + + const dep = new RequireEnsureDependenciesBlock( + expr, + successExpression ? successExpression.fn : successExpressionArg, + errorExpression ? errorExpression.fn : errorExpressionArg, + chunkName, + chunkNameRange, + parser.state.module, + expr.loc + ); + const old = parser.state.current; + parser.state.current = dep; + try { + let failed = false; + parser.inScope([], () => { + for (const ee of dependenciesItems) { + if (ee.isString()) { + const edep = new RequireEnsureItemDependency(ee.string); + edep.loc = dep.loc; + dep.addDependency(edep); + } else { + failed = true; + } + } + }); + if (failed) { + return; + } + if (successExpression) { + if (successExpression.fn.body.type === "BlockStatement") { + parser.walkStatement(successExpression.fn.body); + } else { + parser.walkExpression(successExpression.fn.body); + } + } + old.addBlock(dep); + } finally { + parser.state.current = old; + } + if (!successExpression) { + parser.walkExpression(successExpressionArg); + } + if (errorExpression) { + if (errorExpression.fn.body.type === "BlockStatement") { + parser.walkStatement(errorExpression.fn.body); + } else { + parser.walkExpression(errorExpression.fn.body); + } + } else if (errorExpressionArg) { + parser.walkExpression(errorExpressionArg); + } + return true; + } + } + }); + } +}; diff --git a/node_modules/webpack/lib/dependencies/RequireEnsureDependency.js b/node_modules/webpack/lib/dependencies/RequireEnsureDependency.js index 65a9c8a3f..840130519 100644 --- a/node_modules/webpack/lib/dependencies/RequireEnsureDependency.js +++ b/node_modules/webpack/lib/dependencies/RequireEnsureDependency.js @@ -1,38 +1,58 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const NullDependency = require("./NullDependency");
-const DepBlockHelpers = require("./DepBlockHelpers");
-
-class RequireEnsureDependency extends NullDependency {
- constructor(block) {
- super();
- this.block = block;
- }
-
- get type() {
- return "require.ensure";
- }
-}
-
-RequireEnsureDependency.Template = class RequireEnsureDependencyTemplate {
- apply(dep, source, outputOptions, requestShortener) {
- const depBlock = dep.block;
- const wrapper = DepBlockHelpers.getLoadDepBlockWrapper(depBlock, outputOptions, requestShortener, "require.ensure");
- const errorCallbackExists = depBlock.expr.arguments.length === 4 || (!depBlock.chunkName && depBlock.expr.arguments.length === 3);
- const startBlock = wrapper[0] + "(";
- const middleBlock = `).bind(null, __webpack_require__)${wrapper[1]}`;
- const endBlock = `${middleBlock}__webpack_require__.oe${wrapper[2]}`;
- source.replace(depBlock.expr.range[0], depBlock.expr.arguments[1].range[0] - 1, startBlock);
- if(errorCallbackExists) {
- source.replace(depBlock.expr.arguments[1].range[1], depBlock.expr.arguments[2].range[0] - 1, middleBlock);
- source.replace(depBlock.expr.arguments[2].range[1], depBlock.expr.range[1] - 1, wrapper[2]);
- } else {
- source.replace(depBlock.expr.arguments[1].range[1], depBlock.expr.range[1] - 1, endBlock);
- }
- }
-};
-
-module.exports = RequireEnsureDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const NullDependency = require("./NullDependency"); + +class RequireEnsureDependency extends NullDependency { + constructor(block) { + super(); + this.block = block; + } + + get type() { + return "require.ensure"; + } +} + +RequireEnsureDependency.Template = class RequireEnsureDependencyTemplate { + apply(dep, source, runtime) { + const depBlock = dep.block; + const promise = runtime.blockPromise({ + block: depBlock, + message: "require.ensure" + }); + const errorCallbackExists = + depBlock.expr.arguments.length === 4 || + (!depBlock.chunkName && depBlock.expr.arguments.length === 3); + const startBlock = `${promise}.then((`; + const middleBlock = ").bind(null, __webpack_require__)).catch("; + const endBlock = `).bind(null, __webpack_require__)).catch(${runtime.onError()})`; + source.replace( + depBlock.expr.range[0], + depBlock.expr.arguments[1].range[0] - 1, + startBlock + ); + if (errorCallbackExists) { + source.replace( + depBlock.expr.arguments[1].range[1], + depBlock.expr.arguments[2].range[0] - 1, + middleBlock + ); + source.replace( + depBlock.expr.arguments[2].range[1], + depBlock.expr.range[1] - 1, + ")" + ); + } else { + source.replace( + depBlock.expr.arguments[1].range[1], + depBlock.expr.range[1] - 1, + endBlock + ); + } + } +}; + +module.exports = RequireEnsureDependency; diff --git a/node_modules/webpack/lib/dependencies/RequireEnsureItemDependency.js b/node_modules/webpack/lib/dependencies/RequireEnsureItemDependency.js index ca2b699ae..b4b620bf0 100644 --- a/node_modules/webpack/lib/dependencies/RequireEnsureItemDependency.js +++ b/node_modules/webpack/lib/dependencies/RequireEnsureItemDependency.js @@ -1,21 +1,21 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const ModuleDependency = require("./ModuleDependency");
-const NullDependency = require("./NullDependency");
-
-class RequireEnsureItemDependency extends ModuleDependency {
- constructor(request) {
- super(request);
- }
-
- get type() {
- return "require.ensure item";
- }
-}
-
-RequireEnsureItemDependency.Template = NullDependency.Template;
-
-module.exports = RequireEnsureItemDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const ModuleDependency = require("./ModuleDependency"); +const NullDependency = require("./NullDependency"); + +class RequireEnsureItemDependency extends ModuleDependency { + constructor(request) { + super(request); + } + + get type() { + return "require.ensure item"; + } +} + +RequireEnsureItemDependency.Template = NullDependency.Template; + +module.exports = RequireEnsureItemDependency; diff --git a/node_modules/webpack/lib/dependencies/RequireEnsurePlugin.js b/node_modules/webpack/lib/dependencies/RequireEnsurePlugin.js index b8a66727d..c818e91bc 100644 --- a/node_modules/webpack/lib/dependencies/RequireEnsurePlugin.js +++ b/node_modules/webpack/lib/dependencies/RequireEnsurePlugin.js @@ -1,40 +1,74 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const RequireEnsureItemDependency = require("./RequireEnsureItemDependency");
-const RequireEnsureDependency = require("./RequireEnsureDependency");
-
-const NullFactory = require("../NullFactory");
-
-const RequireEnsureDependenciesBlockParserPlugin = require("./RequireEnsureDependenciesBlockParserPlugin");
-
-const ParserHelpers = require("../ParserHelpers");
-
-class RequireEnsurePlugin {
-
- apply(compiler) {
- compiler.plugin("compilation", (compilation, params) => {
- const normalModuleFactory = params.normalModuleFactory;
-
- compilation.dependencyFactories.set(RequireEnsureItemDependency, normalModuleFactory);
- compilation.dependencyTemplates.set(RequireEnsureItemDependency, new RequireEnsureItemDependency.Template());
-
- compilation.dependencyFactories.set(RequireEnsureDependency, new NullFactory());
- compilation.dependencyTemplates.set(RequireEnsureDependency, new RequireEnsureDependency.Template());
-
- params.normalModuleFactory.plugin("parser", (parser, parserOptions) => {
-
- if(typeof parserOptions.requireEnsure !== "undefined" && !parserOptions.requireEnsure)
- return;
-
- parser.apply(new RequireEnsureDependenciesBlockParserPlugin());
- parser.plugin("evaluate typeof require.ensure", ParserHelpers.evaluateToString("function"));
- parser.plugin("typeof require.ensure", ParserHelpers.toConstantDependency(JSON.stringify("function")));
- });
- });
- }
-}
-module.exports = RequireEnsurePlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const RequireEnsureItemDependency = require("./RequireEnsureItemDependency"); +const RequireEnsureDependency = require("./RequireEnsureDependency"); + +const NullFactory = require("../NullFactory"); + +const RequireEnsureDependenciesBlockParserPlugin = require("./RequireEnsureDependenciesBlockParserPlugin"); + +const ParserHelpers = require("../ParserHelpers"); + +class RequireEnsurePlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "RequireEnsurePlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + RequireEnsureItemDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + RequireEnsureItemDependency, + new RequireEnsureItemDependency.Template() + ); + + compilation.dependencyFactories.set( + RequireEnsureDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + RequireEnsureDependency, + new RequireEnsureDependency.Template() + ); + + const handler = (parser, parserOptions) => { + if ( + parserOptions.requireEnsure !== undefined && + !parserOptions.requireEnsure + ) + return; + + new RequireEnsureDependenciesBlockParserPlugin().apply(parser); + parser.hooks.evaluateTypeof + .for("require.ensure") + .tap( + "RequireEnsurePlugin", + ParserHelpers.evaluateToString("function") + ); + parser.hooks.typeof + .for("require.ensure") + .tap( + "RequireEnsurePlugin", + ParserHelpers.toConstantDependency( + parser, + JSON.stringify("function") + ) + ); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("RequireEnsurePlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("RequireEnsurePlugin", handler); + } + ); + } +} +module.exports = RequireEnsurePlugin; diff --git a/node_modules/webpack/lib/dependencies/RequireHeaderDependency.js b/node_modules/webpack/lib/dependencies/RequireHeaderDependency.js index 7ba24ca0b..6dddd0623 100644 --- a/node_modules/webpack/lib/dependencies/RequireHeaderDependency.js +++ b/node_modules/webpack/lib/dependencies/RequireHeaderDependency.js @@ -1,26 +1,26 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const NullDependency = require("./NullDependency");
-
-class RequireHeaderDependency extends NullDependency {
- constructor(range) {
- super();
- if(!Array.isArray(range)) throw new Error("range must be valid");
- this.range = range;
- }
-}
-
-RequireHeaderDependency.Template = class RequireHeaderDependencyTemplate {
- apply(dep, source) {
- source.replace(dep.range[0], dep.range[1] - 1, "__webpack_require__");
- }
-
- applyAsTemplateArgument(name, dep, source) {
- source.replace(dep.range[0], dep.range[1] - 1, "require");
- }
-};
-
-module.exports = RequireHeaderDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const NullDependency = require("./NullDependency"); + +class RequireHeaderDependency extends NullDependency { + constructor(range) { + super(); + if (!Array.isArray(range)) throw new Error("range must be valid"); + this.range = range; + } +} + +RequireHeaderDependency.Template = class RequireHeaderDependencyTemplate { + apply(dep, source) { + source.replace(dep.range[0], dep.range[1] - 1, "__webpack_require__"); + } + + applyAsTemplateArgument(name, dep, source) { + source.replace(dep.range[0], dep.range[1] - 1, "require"); + } +}; + +module.exports = RequireHeaderDependency; diff --git a/node_modules/webpack/lib/dependencies/RequireIncludeDependency.js b/node_modules/webpack/lib/dependencies/RequireIncludeDependency.js index 1c7829990..9eca57628 100644 --- a/node_modules/webpack/lib/dependencies/RequireIncludeDependency.js +++ b/node_modules/webpack/lib/dependencies/RequireIncludeDependency.js @@ -1,41 +1,39 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const ModuleDependency = require("./ModuleDependency");
-
-class RequireIncludeDependency extends ModuleDependency {
- constructor(request, range) {
- super(request);
- this.range = range;
- }
-
- getReference() {
- if(!this.module) return null;
- return {
- module: this.module,
- importedNames: [] // This doesn't use any export
- };
- }
-
- get type() {
- return "require.include";
- }
-}
-
-RequireIncludeDependency.Template = class RequireIncludeDependencyTemplate {
- apply(dep, source, outputOptions, requestShortener) {
- const comment = this.getOptionalComment(outputOptions.pathinfo && dep.module, requestShortener.shorten(dep.request));
- source.replace(dep.range[0], dep.range[1] - 1, `undefined${comment}`);
- }
-
- getOptionalComment(shouldHaveComment, shortenedRequest) {
- if(shouldHaveComment) {
- return "";
- }
- return `/*! require.include ${shortenedRequest} */`;
- }
-};
-
-module.exports = RequireIncludeDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const DependencyReference = require("./DependencyReference"); +const ModuleDependency = require("./ModuleDependency"); +const Template = require("../Template"); + +class RequireIncludeDependency extends ModuleDependency { + constructor(request, range) { + super(request); + this.range = range; + } + + getReference() { + if (!this.module) return null; + // This doesn't use any export + return new DependencyReference(this.module, [], false); + } + + get type() { + return "require.include"; + } +} + +RequireIncludeDependency.Template = class RequireIncludeDependencyTemplate { + apply(dep, source, runtime) { + const comment = runtime.outputOptions.pathinfo + ? Template.toComment( + `require.include ${runtime.requestShortener.shorten(dep.request)}` + ) + : ""; + source.replace(dep.range[0], dep.range[1] - 1, `undefined${comment}`); + } +}; + +module.exports = RequireIncludeDependency; diff --git a/node_modules/webpack/lib/dependencies/RequireIncludeDependencyParserPlugin.js b/node_modules/webpack/lib/dependencies/RequireIncludeDependencyParserPlugin.js index b7b233145..117e20451 100644 --- a/node_modules/webpack/lib/dependencies/RequireIncludeDependencyParserPlugin.js +++ b/node_modules/webpack/lib/dependencies/RequireIncludeDependencyParserPlugin.js @@ -1,21 +1,23 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const RequireIncludeDependency = require("./RequireIncludeDependency");
-
-module.exports = class RequireIncludeDependencyParserPlugin {
- apply(parser) {
- parser.plugin("call require.include", expr => {
- if(expr.arguments.length !== 1) return;
- const param = parser.evaluateExpression(expr.arguments[0]);
- if(!param.isString()) return;
- const dep = new RequireIncludeDependency(param.string, expr.range);
- dep.loc = expr.loc;
- parser.state.current.addDependency(dep);
- return true;
- });
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const RequireIncludeDependency = require("./RequireIncludeDependency"); + +module.exports = class RequireIncludeDependencyParserPlugin { + apply(parser) { + parser.hooks.call + .for("require.include") + .tap("RequireIncludeDependencyParserPlugin", expr => { + if (expr.arguments.length !== 1) return; + const param = parser.evaluateExpression(expr.arguments[0]); + if (!param.isString()) return; + const dep = new RequireIncludeDependency(param.string, expr.range); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + return true; + }); + } +}; diff --git a/node_modules/webpack/lib/dependencies/RequireIncludePlugin.js b/node_modules/webpack/lib/dependencies/RequireIncludePlugin.js index f80e9b91f..e7d535bc3 100644 --- a/node_modules/webpack/lib/dependencies/RequireIncludePlugin.js +++ b/node_modules/webpack/lib/dependencies/RequireIncludePlugin.js @@ -1,33 +1,61 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const RequireIncludeDependency = require("./RequireIncludeDependency");
-const RequireIncludeDependencyParserPlugin = require("./RequireIncludeDependencyParserPlugin");
-
-const ParserHelpers = require("../ParserHelpers");
-
-class RequireIncludePlugin {
-
- apply(compiler) {
- compiler.plugin("compilation", (compilation, params) => {
- const normalModuleFactory = params.normalModuleFactory;
-
- compilation.dependencyFactories.set(RequireIncludeDependency, normalModuleFactory);
- compilation.dependencyTemplates.set(RequireIncludeDependency, new RequireIncludeDependency.Template());
-
- params.normalModuleFactory.plugin("parser", (parser, parserOptions) => {
-
- if(typeof parserOptions.requireInclude !== "undefined" && !parserOptions.requireInclude)
- return;
-
- parser.apply(new RequireIncludeDependencyParserPlugin());
- parser.plugin("evaluate typeof require.include", ParserHelpers.evaluateToString("function"));
- parser.plugin("typeof require.include", ParserHelpers.toConstantDependency(JSON.stringify("function")));
- });
- });
- }
-}
-module.exports = RequireIncludePlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const RequireIncludeDependency = require("./RequireIncludeDependency"); +const RequireIncludeDependencyParserPlugin = require("./RequireIncludeDependencyParserPlugin"); + +const ParserHelpers = require("../ParserHelpers"); + +class RequireIncludePlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "RequireIncludePlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + RequireIncludeDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + RequireIncludeDependency, + new RequireIncludeDependency.Template() + ); + + const handler = (parser, parserOptions) => { + if ( + parserOptions.requireInclude !== undefined && + !parserOptions.requireInclude + ) + return; + + new RequireIncludeDependencyParserPlugin().apply(parser); + parser.hooks.evaluateTypeof + .for("require.include") + .tap( + "RequireIncludePlugin", + ParserHelpers.evaluateToString("function") + ); + parser.hooks.typeof + .for("require.include") + .tap( + "RequireIncludePlugin", + ParserHelpers.toConstantDependency( + parser, + JSON.stringify("function") + ) + ); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("RequireIncludePlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("RequireIncludePlugin", handler); + } + ); + } +} +module.exports = RequireIncludePlugin; diff --git a/node_modules/webpack/lib/dependencies/RequireResolveContextDependency.js b/node_modules/webpack/lib/dependencies/RequireResolveContextDependency.js index f53e94768..cc40451c9 100644 --- a/node_modules/webpack/lib/dependencies/RequireResolveContextDependency.js +++ b/node_modules/webpack/lib/dependencies/RequireResolveContextDependency.js @@ -1,24 +1,23 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const ContextDependency = require("./ContextDependency");
-const ContextDependencyTemplateAsId = require("./ContextDependencyTemplateAsId");
-
-class RequireResolveContextDependency extends ContextDependency {
- constructor(request, recursive, regExp, range, valueRange) {
- super(request, recursive, regExp);
- this.range = range;
- this.valueRange = valueRange;
- }
-
- get type() {
- return "amd require context";
- }
-
-}
-
-RequireResolveContextDependency.Template = ContextDependencyTemplateAsId;
-
-module.exports = RequireResolveContextDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const ContextDependency = require("./ContextDependency"); +const ContextDependencyTemplateAsId = require("./ContextDependencyTemplateAsId"); + +class RequireResolveContextDependency extends ContextDependency { + constructor(options, range, valueRange) { + super(options); + this.range = range; + this.valueRange = valueRange; + } + + get type() { + return "amd require context"; + } +} + +RequireResolveContextDependency.Template = ContextDependencyTemplateAsId; + +module.exports = RequireResolveContextDependency; diff --git a/node_modules/webpack/lib/dependencies/RequireResolveDependency.js b/node_modules/webpack/lib/dependencies/RequireResolveDependency.js index 72ac48aab..3933baa4b 100644 --- a/node_modules/webpack/lib/dependencies/RequireResolveDependency.js +++ b/node_modules/webpack/lib/dependencies/RequireResolveDependency.js @@ -1,22 +1,22 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const ModuleDependency = require("./ModuleDependency");
-const ModuleDependencyAsId = require("./ModuleDependencyTemplateAsId");
-
-class RequireResolveDependency extends ModuleDependency {
- constructor(request, range) {
- super(request);
- this.range = range;
- }
-
- get type() {
- return "require.resolve";
- }
-}
-
-RequireResolveDependency.Template = ModuleDependencyAsId;
-
-module.exports = RequireResolveDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const ModuleDependency = require("./ModuleDependency"); +const ModuleDependencyAsId = require("./ModuleDependencyTemplateAsId"); + +class RequireResolveDependency extends ModuleDependency { + constructor(request, range) { + super(request); + this.range = range; + } + + get type() { + return "require.resolve"; + } +} + +RequireResolveDependency.Template = ModuleDependencyAsId; + +module.exports = RequireResolveDependency; diff --git a/node_modules/webpack/lib/dependencies/RequireResolveDependencyParserPlugin.js b/node_modules/webpack/lib/dependencies/RequireResolveDependencyParserPlugin.js index 85451cf95..4c51ddf6a 100644 --- a/node_modules/webpack/lib/dependencies/RequireResolveDependencyParserPlugin.js +++ b/node_modules/webpack/lib/dependencies/RequireResolveDependencyParserPlugin.js @@ -1,71 +1,85 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const RequireResolveDependency = require("./RequireResolveDependency");
-const RequireResolveContextDependency = require("./RequireResolveContextDependency");
-const RequireResolveHeaderDependency = require("./RequireResolveHeaderDependency");
-const ContextDependencyHelpers = require("./ContextDependencyHelpers");
-
-class RequireResolveDependencyParserPlugin {
- constructor(options) {
- this.options = options;
- }
-
- apply(parser) {
- const options = this.options;
- parser.plugin("call require.resolve", (expr) => {
- return parser.applyPluginsBailResult("call require.resolve(Weak)", expr, false);
- });
- parser.plugin("call require.resolveWeak", (expr) => {
- return parser.applyPluginsBailResult("call require.resolve(Weak)", expr, true);
- });
- parser.plugin("call require.resolve(Weak)", (expr, weak) => {
- if(expr.arguments.length !== 1) return;
- const param = parser.evaluateExpression(expr.arguments[0]);
- if(param.isConditional()) {
- param.options.forEach((option) => {
- const result = parser.applyPluginsBailResult("call require.resolve(Weak):item", expr, option, weak);
- if(result === undefined) {
- parser.applyPluginsBailResult("call require.resolve(Weak):context", expr, option, weak);
- }
- });
- const dep = new RequireResolveHeaderDependency(expr.callee.range);
- dep.loc = expr.loc;
- parser.state.current.addDependency(dep);
- return true;
- } else {
- const result = parser.applyPluginsBailResult("call require.resolve(Weak):item", expr, param, weak);
- if(result === undefined) {
- parser.applyPluginsBailResult("call require.resolve(Weak):context", expr, param, weak);
- }
- const dep = new RequireResolveHeaderDependency(expr.callee.range);
- dep.loc = expr.loc;
- parser.state.current.addDependency(dep);
- return true;
- }
- });
- parser.plugin("call require.resolve(Weak):item", (expr, param, weak) => {
- if(param.isString()) {
- const dep = new RequireResolveDependency(param.string, param.range);
- dep.loc = expr.loc;
- dep.optional = !!parser.scope.inTry;
- dep.weak = weak;
- parser.state.current.addDependency(dep);
- return true;
- }
- });
- parser.plugin("call require.resolve(Weak):context", (expr, param, weak) => {
- const dep = ContextDependencyHelpers.create(RequireResolveContextDependency, param.range, param, expr, options);
- if(!dep) return;
- dep.loc = expr.loc;
- dep.optional = !!parser.scope.inTry;
- dep.async = weak ? "weak" : false;
- parser.state.current.addDependency(dep);
- return true;
- });
- }
-}
-module.exports = RequireResolveDependencyParserPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const RequireResolveDependency = require("./RequireResolveDependency"); +const RequireResolveContextDependency = require("./RequireResolveContextDependency"); +const RequireResolveHeaderDependency = require("./RequireResolveHeaderDependency"); +const ContextDependencyHelpers = require("./ContextDependencyHelpers"); + +class RequireResolveDependencyParserPlugin { + constructor(options) { + this.options = options; + } + + apply(parser) { + const options = this.options; + + const process = (expr, weak) => { + if (expr.arguments.length !== 1) return; + const param = parser.evaluateExpression(expr.arguments[0]); + if (param.isConditional()) { + for (const option of param.options) { + const result = processItem(expr, option, weak); + if (result === undefined) { + processContext(expr, option, weak); + } + } + const dep = new RequireResolveHeaderDependency(expr.callee.range); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + return true; + } else { + const result = processItem(expr, param, weak); + if (result === undefined) { + processContext(expr, param, weak); + } + const dep = new RequireResolveHeaderDependency(expr.callee.range); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + return true; + } + }; + const processItem = (expr, param, weak) => { + if (param.isString()) { + const dep = new RequireResolveDependency(param.string, param.range); + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + dep.weak = weak; + parser.state.current.addDependency(dep); + return true; + } + }; + const processContext = (expr, param, weak) => { + const dep = ContextDependencyHelpers.create( + RequireResolveContextDependency, + param.range, + param, + expr, + options, + { + mode: weak ? "weak" : "sync" + } + ); + if (!dep) return; + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + }; + + parser.hooks.call + .for("require.resolve") + .tap("RequireResolveDependencyParserPlugin", expr => { + return process(expr, false); + }); + parser.hooks.call + .for("require.resolveWeak") + .tap("RequireResolveDependencyParserPlugin", expr => { + return process(expr, true); + }); + } +} +module.exports = RequireResolveDependencyParserPlugin; diff --git a/node_modules/webpack/lib/dependencies/RequireResolveHeaderDependency.js b/node_modules/webpack/lib/dependencies/RequireResolveHeaderDependency.js index d96ff7ddb..05fe86d69 100644 --- a/node_modules/webpack/lib/dependencies/RequireResolveHeaderDependency.js +++ b/node_modules/webpack/lib/dependencies/RequireResolveHeaderDependency.js @@ -1,26 +1,26 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const NullDependency = require("./NullDependency");
-
-class RequireResolveHeaderDependency extends NullDependency {
- constructor(range) {
- super();
- if(!Array.isArray(range)) throw new Error("range must be valid");
- this.range = range;
- }
-}
-
-RequireResolveHeaderDependency.Template = class RequireResolveHeaderDependencyTemplate {
- apply(dep, source) {
- source.replace(dep.range[0], dep.range[1] - 1, "/*require.resolve*/");
- }
-
- applyAsTemplateArgument(name, dep, source) {
- source.replace(dep.range[0], dep.range[1] - 1, "/*require.resolve*/");
- }
-};
-
-module.exports = RequireResolveHeaderDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const NullDependency = require("./NullDependency"); + +class RequireResolveHeaderDependency extends NullDependency { + constructor(range) { + super(); + if (!Array.isArray(range)) throw new Error("range must be valid"); + this.range = range; + } +} + +RequireResolveHeaderDependency.Template = class RequireResolveHeaderDependencyTemplate { + apply(dep, source) { + source.replace(dep.range[0], dep.range[1] - 1, "/*require.resolve*/"); + } + + applyAsTemplateArgument(name, dep, source) { + source.replace(dep.range[0], dep.range[1] - 1, "/*require.resolve*/"); + } +}; + +module.exports = RequireResolveHeaderDependency; diff --git a/node_modules/webpack/lib/dependencies/SingleEntryDependency.js b/node_modules/webpack/lib/dependencies/SingleEntryDependency.js index 02ccd8986..75a8c080f 100644 --- a/node_modules/webpack/lib/dependencies/SingleEntryDependency.js +++ b/node_modules/webpack/lib/dependencies/SingleEntryDependency.js @@ -1,18 +1,21 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const ModuleDependency = require("./ModuleDependency");
-
-class SingleEntryDependency extends ModuleDependency {
- constructor(request) {
- super(request);
- }
-
- get type() {
- return "single entry";
- }
-}
-
-module.exports = SingleEntryDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const ModuleDependency = require("./ModuleDependency"); + +class SingleEntryDependency extends ModuleDependency { + /** + * @param {string} request request path for entry + */ + constructor(request) { + super(request); + } + + get type() { + return "single entry"; + } +} + +module.exports = SingleEntryDependency; diff --git a/node_modules/webpack/lib/dependencies/SystemPlugin.js b/node_modules/webpack/lib/dependencies/SystemPlugin.js index dd457ae7c..0e3419b57 100644 --- a/node_modules/webpack/lib/dependencies/SystemPlugin.js +++ b/node_modules/webpack/lib/dependencies/SystemPlugin.js @@ -1,44 +1,122 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const ParserHelpers = require("../ParserHelpers");
-
-class SystemPlugin {
- constructor(options) {
- this.options = options;
- }
-
- apply(compiler) {
- compiler.plugin("compilation", (compilation, params) => {
- params.normalModuleFactory.plugin("parser", (parser, parserOptions) => {
-
- if(typeof parserOptions.system !== "undefined" && !parserOptions.system)
- return;
-
- function setNotSupported(name) {
- parser.plugin("evaluate typeof " + name, ParserHelpers.evaluateToString("undefined"));
- parser.plugin("expression " + name,
- ParserHelpers.expressionIsUnsupported(name + " is not supported by webpack.")
- );
- }
-
- parser.plugin("typeof System.import", ParserHelpers.toConstantDependency(JSON.stringify("function")));
- parser.plugin("evaluate typeof System.import", ParserHelpers.evaluateToString("function"));
- parser.plugin("typeof System", ParserHelpers.toConstantDependency(JSON.stringify("object")));
- parser.plugin("evaluate typeof System", ParserHelpers.evaluateToString("object"));
-
- setNotSupported("System.set");
- setNotSupported("System.get");
- setNotSupported("System.register");
- parser.plugin("expression System", function() {
- const systemPolyfillRequire = ParserHelpers.requireFileAsExpression(
- this.state.module.context, require.resolve("../../buildin/system.js"));
- return ParserHelpers.addParsedVariableToModule(this, "System", systemPolyfillRequire);
- });
- });
- });
- }
-}
-module.exports = SystemPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const ParserHelpers = require("../ParserHelpers"); +const WebpackError = require("../WebpackError"); + +class SystemPlugin { + constructor(options) { + this.options = options; + } + + apply(compiler) { + compiler.hooks.compilation.tap( + "SystemPlugin", + (compilation, { normalModuleFactory }) => { + const handler = (parser, parserOptions) => { + if (parserOptions.system !== undefined && !parserOptions.system) + return; + + const shouldWarn = parserOptions.system === undefined; + + const setNotSupported = name => { + parser.hooks.evaluateTypeof + .for(name) + .tap("SystemPlugin", ParserHelpers.evaluateToString("undefined")); + parser.hooks.expression + .for(name) + .tap( + "SystemPlugin", + ParserHelpers.expressionIsUnsupported( + parser, + name + " is not supported by webpack." + ) + ); + }; + + parser.hooks.typeof + .for("System.import") + .tap( + "SystemPlugin", + ParserHelpers.toConstantDependency( + parser, + JSON.stringify("function") + ) + ); + parser.hooks.evaluateTypeof + .for("System.import") + .tap("SystemPlugin", ParserHelpers.evaluateToString("function")); + parser.hooks.typeof + .for("System") + .tap( + "SystemPlugin", + ParserHelpers.toConstantDependency( + parser, + JSON.stringify("object") + ) + ); + parser.hooks.evaluateTypeof + .for("System") + .tap("SystemPlugin", ParserHelpers.evaluateToString("object")); + + setNotSupported("System.set"); + setNotSupported("System.get"); + setNotSupported("System.register"); + + parser.hooks.expression.for("System").tap("SystemPlugin", () => { + const systemPolyfillRequire = ParserHelpers.requireFileAsExpression( + parser.state.module.context, + require.resolve("../../buildin/system") + ); + return ParserHelpers.addParsedVariableToModule( + parser, + "System", + systemPolyfillRequire + ); + }); + + parser.hooks.call.for("System.import").tap("SystemPlugin", expr => { + if (shouldWarn) { + parser.state.module.warnings.push( + new SystemImportDeprecationWarning( + parser.state.module, + expr.loc + ) + ); + } + + return parser.hooks.importCall.call(expr); + }); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("SystemPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("SystemPlugin", handler); + } + ); + } +} + +class SystemImportDeprecationWarning extends WebpackError { + constructor(module, loc) { + super( + "System.import() is deprecated and will be removed soon. Use import() instead.\n" + + "For more info visit https://webpack.js.org/guides/code-splitting/" + ); + + this.name = "SystemImportDeprecationWarning"; + + this.module = module; + this.loc = loc; + + Error.captureStackTrace(this, this.constructor); + } +} + +module.exports = SystemPlugin; diff --git a/node_modules/webpack/lib/dependencies/UnsupportedDependency.js b/node_modules/webpack/lib/dependencies/UnsupportedDependency.js index 48f0971b6..614af783e 100644 --- a/node_modules/webpack/lib/dependencies/UnsupportedDependency.js +++ b/node_modules/webpack/lib/dependencies/UnsupportedDependency.js @@ -1,23 +1,27 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const NullDependency = require("./NullDependency");
-const webpackMissingModule = require("./WebpackMissingModule").module;
-
-class UnsupportedDependency extends NullDependency {
- constructor(request, range) {
- super();
- this.request = request;
- this.range = range;
- }
-}
-
-UnsupportedDependency.Template = class UnsupportedDependencyTemplate {
- apply(dep, source, outputOptions, requestShortener) {
- source.replace(dep.range[0], dep.range[1], webpackMissingModule(dep.request));
- }
-};
-
-module.exports = UnsupportedDependency;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const NullDependency = require("./NullDependency"); +const webpackMissingModule = require("./WebpackMissingModule").module; + +class UnsupportedDependency extends NullDependency { + constructor(request, range) { + super(); + this.request = request; + this.range = range; + } +} + +UnsupportedDependency.Template = class UnsupportedDependencyTemplate { + apply(dep, source, runtime) { + source.replace( + dep.range[0], + dep.range[1], + webpackMissingModule(dep.request) + ); + } +}; + +module.exports = UnsupportedDependency; diff --git a/node_modules/webpack/lib/dependencies/WebpackMissingModule.js b/node_modules/webpack/lib/dependencies/WebpackMissingModule.js index 64e76cffb..a55c9ec08 100644 --- a/node_modules/webpack/lib/dependencies/WebpackMissingModule.js +++ b/node_modules/webpack/lib/dependencies/WebpackMissingModule.js @@ -1,18 +1,20 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const toErrorCode = err => `var e = new Error(${JSON.stringify(err)}); e.code = 'MODULE_NOT_FOUND';`;
-
-exports.module = request => `!(function webpackMissingModule() { ${exports.moduleCode(request)} }())`;
-
-exports.promise = (request) => {
- const errorCode = toErrorCode(`Cannot find module "${request}"`);
- return `Promise.reject(function webpackMissingModule() { ${errorCode}; return e; }())`;
-};
-
-exports.moduleCode = (request) => {
- const errorCode = toErrorCode(`Cannot find module "${request}"`);
- return `${errorCode} throw e;`;
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const toErrorCode = err => + `var e = new Error(${JSON.stringify(err)}); e.code = 'MODULE_NOT_FOUND';`; + +exports.module = request => + `!(function webpackMissingModule() { ${exports.moduleCode(request)} }())`; + +exports.promise = request => { + const errorCode = toErrorCode(`Cannot find module '${request}'`); + return `Promise.reject(function webpackMissingModule() { ${errorCode} return e; }())`; +}; + +exports.moduleCode = request => { + const errorCode = toErrorCode(`Cannot find module '${request}'`); + return `${errorCode} throw e;`; +}; diff --git a/node_modules/webpack/lib/dependencies/getFunctionExpression.js b/node_modules/webpack/lib/dependencies/getFunctionExpression.js index cc32585ab..0e73840e5 100644 --- a/node_modules/webpack/lib/dependencies/getFunctionExpression.js +++ b/node_modules/webpack/lib/dependencies/getFunctionExpression.js @@ -1,44 +1,52 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-module.exports = function(expr) {
- // <FunctionExpression>
- if(expr.type === "FunctionExpression" || expr.type === "ArrowFunctionExpression") {
- return {
- fn: expr,
- expressions: [],
- needThis: false
- };
- }
-
- // <FunctionExpression>.bind(<Expression>)
- if(expr.type === "CallExpression" &&
- expr.callee.type === "MemberExpression" &&
- expr.callee.object.type === "FunctionExpression" &&
- expr.callee.property.type === "Identifier" &&
- expr.callee.property.name === "bind" &&
- expr.arguments.length === 1) {
- return {
- fn: expr.callee.object,
- expressions: [expr.arguments[0]]
- };
- }
- // (function(_this) {return <FunctionExpression>})(this) (Coffeescript)
- if(expr.type === "CallExpression" &&
- expr.callee.type === "FunctionExpression" &&
- expr.callee.body.type === "BlockStatement" &&
- expr.arguments.length === 1 &&
- expr.arguments[0].type === "ThisExpression" &&
- expr.callee.body.body &&
- expr.callee.body.body.length === 1 &&
- expr.callee.body.body[0].type === "ReturnStatement" &&
- expr.callee.body.body[0].argument &&
- expr.callee.body.body[0].argument.type === "FunctionExpression") {
- return {
- fn: expr.callee.body.body[0].argument,
- expressions: [],
- needThis: true
- };
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +module.exports = expr => { + // <FunctionExpression> + if ( + expr.type === "FunctionExpression" || + expr.type === "ArrowFunctionExpression" + ) { + return { + fn: expr, + expressions: [], + needThis: false + }; + } + + // <FunctionExpression>.bind(<Expression>) + if ( + expr.type === "CallExpression" && + expr.callee.type === "MemberExpression" && + expr.callee.object.type === "FunctionExpression" && + expr.callee.property.type === "Identifier" && + expr.callee.property.name === "bind" && + expr.arguments.length === 1 + ) { + return { + fn: expr.callee.object, + expressions: [expr.arguments[0]], + needThis: undefined + }; + } + // (function(_this) {return <FunctionExpression>})(this) (Coffeescript) + if ( + expr.type === "CallExpression" && + expr.callee.type === "FunctionExpression" && + expr.callee.body.type === "BlockStatement" && + expr.arguments.length === 1 && + expr.arguments[0].type === "ThisExpression" && + expr.callee.body.body && + expr.callee.body.body.length === 1 && + expr.callee.body.body[0].type === "ReturnStatement" && + expr.callee.body.body[0].argument && + expr.callee.body.body[0].argument.type === "FunctionExpression" + ) { + return { + fn: expr.callee.body.body[0].argument, + expressions: [], + needThis: true + }; + } +}; diff --git a/node_modules/webpack/lib/formatLocation.js b/node_modules/webpack/lib/formatLocation.js index 046887f6f..f608cd496 100644 --- a/node_modules/webpack/lib/formatLocation.js +++ b/node_modules/webpack/lib/formatLocation.js @@ -1,54 +1,75 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-
-"use strict";
-
-const formatPosition = (pos) => {
- if(pos === null)
- return "";
- const typeOfPos = typeof pos;
- switch(typeOfPos) {
- case "string":
- return pos;
- case "number":
- return `${pos}`;
- case "object":
- if(typeof pos.line === "number" && typeof pos.column === "number")
- return `${pos.line}:${pos.column}`;
- else if(typeof pos.line === "number")
- return `${pos.line}:?`;
- else if(typeof pos.index === "number")
- return `+${pos.index}`;
- else
- return "";
- default:
- return "";
- }
-};
-
-const formatLocation = (loc) => {
- if(loc === null)
- return "";
- const typeOfLoc = typeof loc;
- switch(typeOfLoc) {
- case "string":
- return loc;
- case "number":
- return `${loc}`;
- case "object":
- if(loc.start && loc.end) {
- if(typeof loc.start.line === "number" && typeof loc.end.line === "number" && typeof loc.end.column === "number" && loc.start.line === loc.end.line)
- return `${formatPosition(loc.start)}-${loc.end.column}`;
- return `${formatPosition(loc.start)}-${formatPosition(loc.end)}`;
- }
- if(loc.start)
- return formatPosition(loc.start);
- return formatPosition(loc);
- default:
- return "";
- }
-};
-
-module.exports = formatLocation;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./Dependency").SourcePosition} SourcePosition */ + +// TODO webpack 5: pos must be SourcePosition +/** + * @param {SourcePosition|DependencyLocation|string} pos position + * @returns {string} formatted position + */ +const formatPosition = pos => { + if (pos === null) return ""; + // TODO webpack 5: Simplify this + if (typeof pos === "string") return pos; + if (typeof pos === "number") return `${pos}`; + if (typeof pos === "object") { + if ("line" in pos && "column" in pos) { + return `${pos.line}:${pos.column}`; + } else if ("line" in pos) { + return `${pos.line}:?`; + } else if ("index" in pos) { + // TODO webpack 5 remove this case + return `+${pos.index}`; + } else { + return ""; + } + } + return ""; +}; + +// TODO webpack 5: loc must be DependencyLocation +/** + * @param {DependencyLocation|SourcePosition|string} loc location + * @returns {string} formatted location + */ +const formatLocation = loc => { + if (loc === null) return ""; + // TODO webpack 5: Simplify this + if (typeof loc === "string") return loc; + if (typeof loc === "number") return `${loc}`; + if (typeof loc === "object") { + if ("start" in loc && loc.start && "end" in loc && loc.end) { + if ( + typeof loc.start === "object" && + typeof loc.start.line === "number" && + typeof loc.end === "object" && + typeof loc.end.line === "number" && + typeof loc.end.column === "number" && + loc.start.line === loc.end.line + ) { + return `${formatPosition(loc.start)}-${loc.end.column}`; + } else { + return `${formatPosition(loc.start)}-${formatPosition(loc.end)}`; + } + } + if ("start" in loc && loc.start) { + return formatPosition(loc.start); + } + if ("name" in loc && "index" in loc) { + return `${loc.name}[${loc.index}]`; + } + if ("name" in loc) { + return loc.name; + } + return formatPosition(loc); + } + return ""; +}; + +module.exports = formatLocation; diff --git a/node_modules/webpack/lib/node/NodeChunkTemplatePlugin.js b/node_modules/webpack/lib/node/NodeChunkTemplatePlugin.js index dd5e0e354..292182a97 100644 --- a/node_modules/webpack/lib/node/NodeChunkTemplatePlugin.js +++ b/node_modules/webpack/lib/node/NodeChunkTemplatePlugin.js @@ -1,27 +1,31 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-
-"use strict";
-
-const ConcatSource = require("webpack-sources").ConcatSource;
-
-class NodeChunkTemplatePlugin {
-
- apply(chunkTemplate) {
- chunkTemplate.plugin("render", function(modules, chunk) {
- const source = new ConcatSource();
- source.add(`exports.ids = ${JSON.stringify(chunk.ids)};\nexports.modules = `);
- source.add(modules);
- source.add(";");
- return source;
- });
- chunkTemplate.plugin("hash", function(hash) {
- hash.update("node");
- hash.update("3");
- });
- }
-}
-
-module.exports = NodeChunkTemplatePlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { ConcatSource } = require("webpack-sources"); + +class NodeChunkTemplatePlugin { + apply(chunkTemplate) { + chunkTemplate.hooks.render.tap( + "NodeChunkTemplatePlugin", + (modules, chunk) => { + const source = new ConcatSource(); + source.add( + `exports.ids = ${JSON.stringify(chunk.ids)};\nexports.modules = ` + ); + source.add(modules); + source.add(";"); + return source; + } + ); + chunkTemplate.hooks.hash.tap("NodeChunkTemplatePlugin", hash => { + hash.update("node"); + hash.update("3"); + }); + } +} + +module.exports = NodeChunkTemplatePlugin; diff --git a/node_modules/webpack/lib/node/NodeEnvironmentPlugin.js b/node_modules/webpack/lib/node/NodeEnvironmentPlugin.js index b8200a3ca..3f76bffa5 100644 --- a/node_modules/webpack/lib/node/NodeEnvironmentPlugin.js +++ b/node_modules/webpack/lib/node/NodeEnvironmentPlugin.js @@ -1,25 +1,28 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const NodeWatchFileSystem = require("./NodeWatchFileSystem");
-const NodeOutputFileSystem = require("./NodeOutputFileSystem");
-const NodeJsInputFileSystem = require("enhanced-resolve/lib/NodeJsInputFileSystem");
-const CachedInputFileSystem = require("enhanced-resolve/lib/CachedInputFileSystem");
-
-class NodeEnvironmentPlugin {
- apply(compiler) {
- compiler.inputFileSystem = new CachedInputFileSystem(new NodeJsInputFileSystem(), 60000);
- const inputFileSystem = compiler.inputFileSystem;
- compiler.outputFileSystem = new NodeOutputFileSystem();
- compiler.watchFileSystem = new NodeWatchFileSystem(compiler.inputFileSystem);
- compiler.plugin("before-run", (compiler, callback) => {
- if(compiler.inputFileSystem === inputFileSystem)
- inputFileSystem.purge();
- callback();
- });
- }
-}
-module.exports = NodeEnvironmentPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const NodeWatchFileSystem = require("./NodeWatchFileSystem"); +const NodeOutputFileSystem = require("./NodeOutputFileSystem"); +const NodeJsInputFileSystem = require("enhanced-resolve/lib/NodeJsInputFileSystem"); +const CachedInputFileSystem = require("enhanced-resolve/lib/CachedInputFileSystem"); + +class NodeEnvironmentPlugin { + apply(compiler) { + compiler.inputFileSystem = new CachedInputFileSystem( + new NodeJsInputFileSystem(), + 60000 + ); + const inputFileSystem = compiler.inputFileSystem; + compiler.outputFileSystem = new NodeOutputFileSystem(); + compiler.watchFileSystem = new NodeWatchFileSystem( + compiler.inputFileSystem + ); + compiler.hooks.beforeRun.tap("NodeEnvironmentPlugin", compiler => { + if (compiler.inputFileSystem === inputFileSystem) inputFileSystem.purge(); + }); + } +} +module.exports = NodeEnvironmentPlugin; diff --git a/node_modules/webpack/lib/node/NodeHotUpdateChunkTemplatePlugin.js b/node_modules/webpack/lib/node/NodeHotUpdateChunkTemplatePlugin.js index 52239f7b6..bbd2e12a6 100644 --- a/node_modules/webpack/lib/node/NodeHotUpdateChunkTemplatePlugin.js +++ b/node_modules/webpack/lib/node/NodeHotUpdateChunkTemplatePlugin.js @@ -1,27 +1,36 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const ConcatSource = require("webpack-sources").ConcatSource;
-
-class NodeHotUpdateChunkTemplatePlugin {
-
- apply(hotUpdateChunkTemplate) {
- hotUpdateChunkTemplate.plugin("render", (modulesSource, modules, removedModules, hash, id) => {
- const source = new ConcatSource();
- source.add("exports.id = " + JSON.stringify(id) + ";\nexports.modules = ");
- source.add(modulesSource);
- source.add(";");
- return source;
- });
- hotUpdateChunkTemplate.plugin("hash", function(hash) {
- hash.update("NodeHotUpdateChunkTemplatePlugin");
- hash.update("3");
- hash.update(this.outputOptions.hotUpdateFunction + "");
- hash.update(this.outputOptions.library + "");
- });
- }
-}
-module.exports = NodeHotUpdateChunkTemplatePlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const { ConcatSource } = require("webpack-sources"); + +class NodeHotUpdateChunkTemplatePlugin { + apply(hotUpdateChunkTemplate) { + hotUpdateChunkTemplate.hooks.render.tap( + "NodeHotUpdateChunkTemplatePlugin", + (modulesSource, modules, removedModules, hash, id) => { + const source = new ConcatSource(); + source.add( + "exports.id = " + JSON.stringify(id) + ";\nexports.modules = " + ); + source.add(modulesSource); + source.add(";"); + return source; + } + ); + hotUpdateChunkTemplate.hooks.hash.tap( + "NodeHotUpdateChunkTemplatePlugin", + hash => { + hash.update("NodeHotUpdateChunkTemplatePlugin"); + hash.update("3"); + hash.update( + hotUpdateChunkTemplate.outputOptions.hotUpdateFunction + "" + ); + hash.update(hotUpdateChunkTemplate.outputOptions.library + ""); + } + ); + } +} +module.exports = NodeHotUpdateChunkTemplatePlugin; diff --git a/node_modules/webpack/lib/node/NodeMainTemplate.runtime.js b/node_modules/webpack/lib/node/NodeMainTemplate.runtime.js index 2725e2e79..d34388bf7 100644 --- a/node_modules/webpack/lib/node/NodeMainTemplate.runtime.js +++ b/node_modules/webpack/lib/node/NodeMainTemplate.runtime.js @@ -1,24 +1,27 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-/*global installedChunks $hotChunkFilename$ hotAddUpdateChunk $hotMainFilename$ */
-module.exports = function() {
- function hotDownloadUpdateChunk(chunkId) { // eslint-disable-line no-unused-vars
- var chunk = require("./" + $hotChunkFilename$);
- hotAddUpdateChunk(chunk.id, chunk.modules);
- }
-
- function hotDownloadManifest() { // eslint-disable-line no-unused-vars
- try {
- var update = require("./" + $hotMainFilename$);
- } catch(e) {
- return Promise.resolve();
- }
- return Promise.resolve(update);
- }
-
- function hotDisposeChunk(chunkId) { //eslint-disable-line no-unused-vars
- delete installedChunks[chunkId];
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +/*global installedChunks $hotChunkFilename$ hotAddUpdateChunk $hotMainFilename$ */ +module.exports = function() { + // eslint-disable-next-line no-unused-vars + function hotDownloadUpdateChunk(chunkId) { + var chunk = require("./" + $hotChunkFilename$); + hotAddUpdateChunk(chunk.id, chunk.modules); + } + + // eslint-disable-next-line no-unused-vars + function hotDownloadManifest() { + try { + var update = require("./" + $hotMainFilename$); + } catch (e) { + return Promise.resolve(); + } + return Promise.resolve(update); + } + + //eslint-disable-next-line no-unused-vars + function hotDisposeChunk(chunkId) { + delete installedChunks[chunkId]; + } +}; diff --git a/node_modules/webpack/lib/node/NodeMainTemplateAsync.runtime.js b/node_modules/webpack/lib/node/NodeMainTemplateAsync.runtime.js index 673cfafd0..35eb47b66 100644 --- a/node_modules/webpack/lib/node/NodeMainTemplateAsync.runtime.js +++ b/node_modules/webpack/lib/node/NodeMainTemplateAsync.runtime.js @@ -1,40 +1,44 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-/*global installedChunks $hotChunkFilename$ $require$ hotAddUpdateChunk $hotMainFilename$ */
-module.exports = function() {
- function hotDownloadUpdateChunk(chunkId) { // eslint-disable-line no-unused-vars
- var filename = require("path").join(__dirname, $hotChunkFilename$);
- require("fs").readFile(filename, "utf-8", function(err, content) {
- if(err) {
- if($require$.onError)
- return $require$.oe(err);
- else
- throw err;
- }
- var chunk = {};
- require("vm").runInThisContext("(function(exports) {" + content + "\n})", filename)(chunk);
- hotAddUpdateChunk(chunk.id, chunk.modules);
- });
- }
-
- function hotDownloadManifest() { // eslint-disable-line no-unused-vars
- var filename = require("path").join(__dirname, $hotMainFilename$);
- return new Promise(function(resolve, reject) {
- require("fs").readFile(filename, "utf-8", function(err, content) {
- if(err) return resolve();
- try {
- var update = JSON.parse(content);
- } catch(e) {
- return reject(e);
- }
- resolve(update);
- });
- });
- }
-
- function hotDisposeChunk(chunkId) { //eslint-disable-line no-unused-vars
- delete installedChunks[chunkId];
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +/*global installedChunks $hotChunkFilename$ $require$ hotAddUpdateChunk $hotMainFilename$ */ +module.exports = function() { + // eslint-disable-next-line no-unused-vars + function hotDownloadUpdateChunk(chunkId) { + var filename = require("path").join(__dirname, $hotChunkFilename$); + require("fs").readFile(filename, "utf-8", function(err, content) { + if (err) { + if ($require$.onError) return $require$.oe(err); + throw err; + } + var chunk = {}; + require("vm").runInThisContext( + "(function(exports) {" + content + "\n})", + { filename: filename } + )(chunk); + hotAddUpdateChunk(chunk.id, chunk.modules); + }); + } + + // eslint-disable-next-line no-unused-vars + function hotDownloadManifest() { + var filename = require("path").join(__dirname, $hotMainFilename$); + return new Promise(function(resolve, reject) { + require("fs").readFile(filename, "utf-8", function(err, content) { + if (err) return resolve(); + try { + var update = JSON.parse(content); + } catch (e) { + return reject(e); + } + resolve(update); + }); + }); + } + + // eslint-disable-next-line no-unused-vars + function hotDisposeChunk(chunkId) { + delete installedChunks[chunkId]; + } +}; diff --git a/node_modules/webpack/lib/node/NodeMainTemplatePlugin.js b/node_modules/webpack/lib/node/NodeMainTemplatePlugin.js index 9a64b57b5..a27029699 100644 --- a/node_modules/webpack/lib/node/NodeMainTemplatePlugin.js +++ b/node_modules/webpack/lib/node/NodeMainTemplatePlugin.js @@ -1,183 +1,321 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const Template = require("../Template");
-
-module.exports = class NodeMainTemplatePlugin {
- constructor(asyncChunkLoading) {
- this.asyncChunkLoading = asyncChunkLoading;
- }
-
- apply(mainTemplate) {
- const asyncChunkLoading = this.asyncChunkLoading;
- mainTemplate.plugin("local-vars", function(source, chunk) {
- if(chunk.chunks.length > 0) {
- return this.asString([
- source,
- "",
- "// object to store loaded chunks",
- "// \"0\" means \"already loaded\"",
- "var installedChunks = {",
- this.indent(chunk.ids.map((id) => `${id}: 0`).join(",\n")),
- "};"
- ]);
- }
- return source;
- });
- mainTemplate.plugin("require-extensions", function(source, chunk) {
- if(chunk.chunks.length > 0) {
- return this.asString([
- source,
- "",
- "// uncatched error handler for webpack runtime",
- `${this.requireFn}.oe = function(err) {`,
- this.indent([
- "process.nextTick(function() {",
- this.indent("throw err; // catch this error by using System.import().catch()"),
- "});"
- ]),
- "};"
- ]);
- }
- return source;
- });
- mainTemplate.plugin("require-ensure", function(_, chunk, hash) {
- const chunkFilename = this.outputOptions.chunkFilename;
- const chunkMaps = chunk.getChunkMaps();
- const insertMoreModules = [
- "var moreModules = chunk.modules, chunkIds = chunk.ids;",
- "for(var moduleId in moreModules) {",
- this.indent(this.renderAddModule(hash, chunk, "moduleId", "moreModules[moduleId]")),
- "}"
- ];
- if(asyncChunkLoading) {
- return this.asString([
- "// \"0\" is the signal for \"already loaded\"",
- "if(installedChunks[chunkId] === 0)",
- this.indent([
- "return Promise.resolve();"
- ]),
- "// array of [resolve, reject, promise] means \"currently loading\"",
- "if(installedChunks[chunkId])",
- this.indent([
- "return installedChunks[chunkId][2];"
- ]),
- "// load the chunk and return promise to it",
- "var promise = new Promise(function(resolve, reject) {",
- this.indent([
- "installedChunks[chunkId] = [resolve, reject];",
- "var filename = __dirname + " + this.applyPluginsWaterfall("asset-path", JSON.stringify(`/${chunkFilename}`), {
- hash: `" + ${this.renderCurrentHashCode(hash)} + "`,
- hashWithLength: (length) => `" + ${this.renderCurrentHashCode(hash, length)} + "`,
- chunk: {
- id: "\" + chunkId + \"",
- hash: `" + ${JSON.stringify(chunkMaps.hash)}[chunkId] + "`,
- hashWithLength: (length) => {
- const shortChunkHashMap = {};
- Object.keys(chunkMaps.hash).forEach((chunkId) => {
- if(typeof chunkMaps.hash[chunkId] === "string")
- shortChunkHashMap[chunkId] = chunkMaps.hash[chunkId].substr(0, length);
- });
- return `" + ${JSON.stringify(shortChunkHashMap)}[chunkId] + "`;
- },
- name: `" + (${JSON.stringify(chunkMaps.name)}[chunkId]||chunkId) + "`
- }
- }) + ";",
- "require('fs').readFile(filename, 'utf-8', function(err, content) {",
- this.indent([
- "if(err) return reject(err);",
- "var chunk = {};",
- "require('vm').runInThisContext('(function(exports, require, __dirname, __filename) {' + content + '\\n})', filename)" +
- "(chunk, require, require('path').dirname(filename), filename);"
- ].concat(insertMoreModules).concat([
- "var callbacks = [];",
- "for(var i = 0; i < chunkIds.length; i++) {",
- this.indent([
- "if(installedChunks[chunkIds[i]])",
- this.indent([
- "callbacks = callbacks.concat(installedChunks[chunkIds[i]][0]);"
- ]),
- "installedChunks[chunkIds[i]] = 0;"
- ]),
- "}",
- "for(i = 0; i < callbacks.length; i++)",
- this.indent("callbacks[i]();")
- ])),
- "});"
- ]),
- "});",
- "return installedChunks[chunkId][2] = promise;"
- ]);
- } else {
- const request = this.applyPluginsWaterfall("asset-path", JSON.stringify(`./${chunkFilename}`), {
- hash: `" + ${this.renderCurrentHashCode(hash)} + "`,
- hashWithLength: (length) => `" + ${this.renderCurrentHashCode(hash, length)} + "`,
- chunk: {
- id: "\" + chunkId + \"",
- hash: `" + ${JSON.stringify(chunkMaps.hash)}[chunkId] + "`,
- hashWithLength: (length) => {
- const shortChunkHashMap = {};
- Object.keys(chunkMaps.hash).forEach((chunkId) => {
- if(typeof chunkMaps.hash[chunkId] === "string")
- shortChunkHashMap[chunkId] = chunkMaps.hash[chunkId].substr(0, length);
- });
- return `" + ${JSON.stringify(shortChunkHashMap)}[chunkId] + "`;
- },
- name: `" + (${JSON.stringify(chunkMaps.name)}[chunkId]||chunkId) + "`
- }
- });
- return this.asString([
- "// \"0\" is the signal for \"already loaded\"",
- "if(installedChunks[chunkId] !== 0) {",
- this.indent([
- `var chunk = require(${request});`
- ].concat(insertMoreModules).concat([
- "for(var i = 0; i < chunkIds.length; i++)",
- this.indent("installedChunks[chunkIds[i]] = 0;")
- ])),
- "}",
- "return Promise.resolve();"
- ]);
- }
- });
- mainTemplate.plugin("hot-bootstrap", function(source, chunk, hash) {
- const hotUpdateChunkFilename = this.outputOptions.hotUpdateChunkFilename;
- const hotUpdateMainFilename = this.outputOptions.hotUpdateMainFilename;
- const chunkMaps = chunk.getChunkMaps();
- const currentHotUpdateChunkFilename = this.applyPluginsWaterfall("asset-path", JSON.stringify(hotUpdateChunkFilename), {
- hash: `" + ${this.renderCurrentHashCode(hash)} + "`,
- hashWithLength: (length) => `" + ${this.renderCurrentHashCode(hash, length)} + "`,
- chunk: {
- id: "\" + chunkId + \"",
- hash: `" + ${JSON.stringify(chunkMaps.hash)}[chunkId] + "`,
- hashWithLength: (length) => {
- const shortChunkHashMap = {};
- Object.keys(chunkMaps.hash).forEach((chunkId) => {
- if(typeof chunkMaps.hash[chunkId] === "string")
- shortChunkHashMap[chunkId] = chunkMaps.hash[chunkId].substr(0, length);
- });
- return `" + ${JSON.stringify(shortChunkHashMap)}[chunkId] + "`;
- },
- name: `" + (${JSON.stringify(chunkMaps.name)}[chunkId]||chunkId) + "`
- }
- });
- const currentHotUpdateMainFilename = this.applyPluginsWaterfall("asset-path", JSON.stringify(hotUpdateMainFilename), {
- hash: `" + ${this.renderCurrentHashCode(hash)} + "`,
- hashWithLength: (length) => `" + ${this.renderCurrentHashCode(hash, length)} + "`
- });
- return Template.getFunctionContent(asyncChunkLoading ? require("./NodeMainTemplateAsync.runtime.js") : require("./NodeMainTemplate.runtime.js"))
- .replace(/\$require\$/g, this.requireFn)
- .replace(/\$hotMainFilename\$/g, currentHotUpdateMainFilename)
- .replace(/\$hotChunkFilename\$/g, currentHotUpdateChunkFilename);
- });
- mainTemplate.plugin("hash", function(hash) {
- hash.update("node");
- hash.update("3");
- hash.update(this.outputOptions.filename + "");
- hash.update(this.outputOptions.chunkFilename + "");
- });
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Template = require("../Template"); + +module.exports = class NodeMainTemplatePlugin { + constructor(asyncChunkLoading) { + this.asyncChunkLoading = asyncChunkLoading; + } + + apply(mainTemplate) { + const needChunkOnDemandLoadingCode = chunk => { + for (const chunkGroup of chunk.groupsIterable) { + if (chunkGroup.getNumberOfChildren() > 0) return true; + } + return false; + }; + const asyncChunkLoading = this.asyncChunkLoading; + mainTemplate.hooks.localVars.tap( + "NodeMainTemplatePlugin", + (source, chunk) => { + if (needChunkOnDemandLoadingCode(chunk)) { + return Template.asString([ + source, + "", + "// object to store loaded chunks", + '// "0" means "already loaded"', + "var installedChunks = {", + Template.indent( + chunk.ids.map(id => `${JSON.stringify(id)}: 0`).join(",\n") + ), + "};" + ]); + } + return source; + } + ); + mainTemplate.hooks.requireExtensions.tap( + "NodeMainTemplatePlugin", + (source, chunk) => { + if (needChunkOnDemandLoadingCode(chunk)) { + return Template.asString([ + source, + "", + "// uncaught error handler for webpack runtime", + `${mainTemplate.requireFn}.oe = function(err) {`, + Template.indent([ + "process.nextTick(function() {", + Template.indent( + "throw err; // catch this error by using import().catch()" + ), + "});" + ]), + "};" + ]); + } + return source; + } + ); + mainTemplate.hooks.requireEnsure.tap( + "NodeMainTemplatePlugin", + (source, chunk, hash) => { + const chunkFilename = mainTemplate.outputOptions.chunkFilename; + const chunkMaps = chunk.getChunkMaps(); + const insertMoreModules = [ + "var moreModules = chunk.modules, chunkIds = chunk.ids;", + "for(var moduleId in moreModules) {", + Template.indent( + mainTemplate.renderAddModule( + hash, + chunk, + "moduleId", + "moreModules[moduleId]" + ) + ), + "}" + ]; + if (asyncChunkLoading) { + return Template.asString([ + source, + "", + "// ReadFile + VM.run chunk loading for javascript", + "", + "var installedChunkData = installedChunks[chunkId];", + 'if(installedChunkData !== 0) { // 0 means "already installed".', + Template.indent([ + '// array of [resolve, reject, promise] means "currently loading"', + "if(installedChunkData) {", + Template.indent(["promises.push(installedChunkData[2]);"]), + "} else {", + Template.indent([ + "// load the chunk and return promise to it", + "var promise = new Promise(function(resolve, reject) {", + Template.indent([ + "installedChunkData = installedChunks[chunkId] = [resolve, reject];", + "var filename = require('path').join(__dirname, " + + mainTemplate.getAssetPath( + JSON.stringify(`/${chunkFilename}`), + { + hash: `" + ${mainTemplate.renderCurrentHashCode( + hash + )} + "`, + hashWithLength: length => + `" + ${mainTemplate.renderCurrentHashCode( + hash, + length + )} + "`, + chunk: { + id: '" + chunkId + "', + hash: `" + ${JSON.stringify( + chunkMaps.hash + )}[chunkId] + "`, + hashWithLength: length => { + const shortChunkHashMap = {}; + for (const chunkId of Object.keys(chunkMaps.hash)) { + if (typeof chunkMaps.hash[chunkId] === "string") { + shortChunkHashMap[chunkId] = chunkMaps.hash[ + chunkId + ].substr(0, length); + } + } + return `" + ${JSON.stringify( + shortChunkHashMap + )}[chunkId] + "`; + }, + contentHash: { + javascript: `" + ${JSON.stringify( + chunkMaps.contentHash.javascript + )}[chunkId] + "` + }, + contentHashWithLength: { + javascript: length => { + const shortContentHashMap = {}; + const contentHash = + chunkMaps.contentHash.javascript; + for (const chunkId of Object.keys(contentHash)) { + if (typeof contentHash[chunkId] === "string") { + shortContentHashMap[chunkId] = contentHash[ + chunkId + ].substr(0, length); + } + } + return `" + ${JSON.stringify( + shortContentHashMap + )}[chunkId] + "`; + } + }, + name: `" + (${JSON.stringify( + chunkMaps.name + )}[chunkId]||chunkId) + "` + }, + contentHashType: "javascript" + } + ) + + ");", + "require('fs').readFile(filename, 'utf-8', function(err, content) {", + Template.indent( + [ + "if(err) return reject(err);", + "var chunk = {};", + "require('vm').runInThisContext('(function(exports, require, __dirname, __filename) {' + content + '\\n})', filename)" + + "(chunk, require, require('path').dirname(filename), filename);" + ] + .concat(insertMoreModules) + .concat([ + "var callbacks = [];", + "for(var i = 0; i < chunkIds.length; i++) {", + Template.indent([ + "if(installedChunks[chunkIds[i]])", + Template.indent([ + "callbacks = callbacks.concat(installedChunks[chunkIds[i]][0]);" + ]), + "installedChunks[chunkIds[i]] = 0;" + ]), + "}", + "for(i = 0; i < callbacks.length; i++)", + Template.indent("callbacks[i]();") + ]) + ), + "});" + ]), + "});", + "promises.push(installedChunkData[2] = promise);" + ]), + "}" + ]), + "}" + ]); + } else { + const request = mainTemplate.getAssetPath( + JSON.stringify(`./${chunkFilename}`), + { + hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, + hashWithLength: length => + `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`, + chunk: { + id: '" + chunkId + "', + hash: `" + ${JSON.stringify(chunkMaps.hash)}[chunkId] + "`, + hashWithLength: length => { + const shortChunkHashMap = {}; + for (const chunkId of Object.keys(chunkMaps.hash)) { + if (typeof chunkMaps.hash[chunkId] === "string") { + shortChunkHashMap[chunkId] = chunkMaps.hash[ + chunkId + ].substr(0, length); + } + } + return `" + ${JSON.stringify( + shortChunkHashMap + )}[chunkId] + "`; + }, + contentHash: { + javascript: `" + ${JSON.stringify( + chunkMaps.contentHash.javascript + )}[chunkId] + "` + }, + contentHashWithLength: { + javascript: length => { + const shortContentHashMap = {}; + const contentHash = chunkMaps.contentHash.javascript; + for (const chunkId of Object.keys(contentHash)) { + if (typeof contentHash[chunkId] === "string") { + shortContentHashMap[chunkId] = contentHash[ + chunkId + ].substr(0, length); + } + } + return `" + ${JSON.stringify( + shortContentHashMap + )}[chunkId] + "`; + } + }, + name: `" + (${JSON.stringify( + chunkMaps.name + )}[chunkId]||chunkId) + "` + }, + contentHashType: "javascript" + } + ); + return Template.asString([ + source, + "", + "// require() chunk loading for javascript", + "", + '// "0" is the signal for "already loaded"', + "if(installedChunks[chunkId] !== 0) {", + Template.indent( + [`var chunk = require(${request});`] + .concat(insertMoreModules) + .concat([ + "for(var i = 0; i < chunkIds.length; i++)", + Template.indent("installedChunks[chunkIds[i]] = 0;") + ]) + ), + "}" + ]); + } + } + ); + mainTemplate.hooks.hotBootstrap.tap( + "NodeMainTemplatePlugin", + (source, chunk, hash) => { + const hotUpdateChunkFilename = + mainTemplate.outputOptions.hotUpdateChunkFilename; + const hotUpdateMainFilename = + mainTemplate.outputOptions.hotUpdateMainFilename; + const chunkMaps = chunk.getChunkMaps(); + const currentHotUpdateChunkFilename = mainTemplate.getAssetPath( + JSON.stringify(hotUpdateChunkFilename), + { + hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, + hashWithLength: length => + `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`, + chunk: { + id: '" + chunkId + "', + hash: `" + ${JSON.stringify(chunkMaps.hash)}[chunkId] + "`, + hashWithLength: length => { + const shortChunkHashMap = {}; + for (const chunkId of Object.keys(chunkMaps.hash)) { + if (typeof chunkMaps.hash[chunkId] === "string") { + shortChunkHashMap[chunkId] = chunkMaps.hash[chunkId].substr( + 0, + length + ); + } + } + return `" + ${JSON.stringify(shortChunkHashMap)}[chunkId] + "`; + }, + name: `" + (${JSON.stringify( + chunkMaps.name + )}[chunkId]||chunkId) + "` + } + } + ); + const currentHotUpdateMainFilename = mainTemplate.getAssetPath( + JSON.stringify(hotUpdateMainFilename), + { + hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, + hashWithLength: length => + `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "` + } + ); + return Template.getFunctionContent( + asyncChunkLoading + ? require("./NodeMainTemplateAsync.runtime") + : require("./NodeMainTemplate.runtime") + ) + .replace(/\$require\$/g, mainTemplate.requireFn) + .replace(/\$hotMainFilename\$/g, currentHotUpdateMainFilename) + .replace(/\$hotChunkFilename\$/g, currentHotUpdateChunkFilename); + } + ); + mainTemplate.hooks.hash.tap("NodeMainTemplatePlugin", hash => { + hash.update("node"); + hash.update("4"); + }); + } +}; diff --git a/node_modules/webpack/lib/node/NodeOutputFileSystem.js b/node_modules/webpack/lib/node/NodeOutputFileSystem.js index 5a6e328e1..2789b576a 100644 --- a/node_modules/webpack/lib/node/NodeOutputFileSystem.js +++ b/node_modules/webpack/lib/node/NodeOutputFileSystem.js @@ -1,22 +1,22 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const fs = require("fs");
-const path = require("path");
-const mkdirp = require("mkdirp");
-
-class NodeOutputFileSystem {
- constructor() {
- this.mkdirp = mkdirp;
- this.mkdir = fs.mkdir.bind(fs);
- this.rmdir = fs.rmdir.bind(fs);
- this.unlink = fs.unlink.bind(fs);
- this.writeFile = fs.writeFile.bind(fs);
- this.join = path.join.bind(path);
- }
-}
-
-module.exports = NodeOutputFileSystem;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const fs = require("fs"); +const path = require("path"); +const mkdirp = require("mkdirp"); + +class NodeOutputFileSystem { + constructor() { + this.mkdirp = mkdirp; + this.mkdir = fs.mkdir.bind(fs); + this.rmdir = fs.rmdir.bind(fs); + this.unlink = fs.unlink.bind(fs); + this.writeFile = fs.writeFile.bind(fs); + this.join = path.join.bind(path); + } +} + +module.exports = NodeOutputFileSystem; diff --git a/node_modules/webpack/lib/node/NodeSourcePlugin.js b/node_modules/webpack/lib/node/NodeSourcePlugin.js index 986160028..d5505f6f5 100644 --- a/node_modules/webpack/lib/node/NodeSourcePlugin.js +++ b/node_modules/webpack/lib/node/NodeSourcePlugin.js @@ -1,88 +1,144 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const AliasPlugin = require("enhanced-resolve/lib/AliasPlugin");
-const ParserHelpers = require("../ParserHelpers");
-const nodeLibsBrowser = require("node-libs-browser");
-
-module.exports = class NodeSourcePlugin {
- constructor(options) {
- this.options = options;
- }
- apply(compiler) {
- const options = this.options;
- if(options === false) // allow single kill switch to turn off this plugin
- return;
-
- function getPathToModule(module, type) {
- if(type === true || (type === undefined && nodeLibsBrowser[module])) {
- if(!nodeLibsBrowser[module]) throw new Error(`No browser version for node.js core module ${module} available`);
- return nodeLibsBrowser[module];
- } else if(type === "mock") {
- return require.resolve(`node-libs-browser/mock/${module}`);
- } else if(type === "empty") {
- return require.resolve("node-libs-browser/mock/empty");
- } else return module;
- }
-
- function addExpression(parser, name, module, type, suffix) {
- suffix = suffix || "";
- parser.plugin(`expression ${name}`, function() {
- if(this.state.module && this.state.module.resource === getPathToModule(module, type)) return;
- const mockModule = ParserHelpers.requireFileAsExpression(this.state.module.context, getPathToModule(module, type));
- return ParserHelpers.addParsedVariableToModule(this, name, mockModule + suffix);
- });
- }
-
- compiler.plugin("compilation", function(compilation, params) {
- params.normalModuleFactory.plugin("parser", function(parser, parserOptions) {
-
- if(parserOptions.node === false)
- return;
-
- let localOptions = options;
- if(parserOptions.node)
- localOptions = Object.assign({}, localOptions, parserOptions.node);
-
- if(localOptions.global) {
- parser.plugin("expression global", function() {
- const retrieveGlobalModule = ParserHelpers.requireFileAsExpression(this.state.module.context, require.resolve("../../buildin/global.js"));
- return ParserHelpers.addParsedVariableToModule(this, "global", retrieveGlobalModule);
- });
- }
- if(localOptions.process) {
- const processType = localOptions.process;
- addExpression(parser, "process", "process", processType);
- }
- if(localOptions.console) {
- const consoleType = localOptions.console;
- addExpression(parser, "console", "console", consoleType);
- }
- const bufferType = localOptions.Buffer;
- if(bufferType) {
- addExpression(parser, "Buffer", "buffer", bufferType, ".Buffer");
- }
- if(localOptions.setImmediate) {
- const setImmediateType = localOptions.setImmediate;
- addExpression(parser, "setImmediate", "timers", setImmediateType, ".setImmediate");
- addExpression(parser, "clearImmediate", "timers", setImmediateType, ".clearImmediate");
- }
- });
- });
- compiler.plugin("after-resolvers", (compiler) => {
- Object.keys(nodeLibsBrowser).forEach((lib) => {
- if(options[lib] !== false) {
- compiler.resolvers.normal.apply(
- new AliasPlugin("described-resolve", {
- name: lib,
- onlyModule: true,
- alias: getPathToModule(lib, options[lib])
- }, "resolve")
- );
- }
- });
- });
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const AliasPlugin = require("enhanced-resolve/lib/AliasPlugin"); +const ParserHelpers = require("../ParserHelpers"); +const nodeLibsBrowser = require("node-libs-browser"); + +module.exports = class NodeSourcePlugin { + constructor(options) { + this.options = options; + } + apply(compiler) { + const options = this.options; + if (options === false) { + // allow single kill switch to turn off this plugin + return; + } + + const getPathToModule = (module, type) => { + if (type === true || (type === undefined && nodeLibsBrowser[module])) { + if (!nodeLibsBrowser[module]) { + throw new Error( + `No browser version for node.js core module ${module} available` + ); + } + return nodeLibsBrowser[module]; + } else if (type === "mock") { + return require.resolve(`node-libs-browser/mock/${module}`); + } else if (type === "empty") { + return require.resolve("node-libs-browser/mock/empty"); + } else { + return module; + } + }; + + const addExpression = (parser, name, module, type, suffix) => { + suffix = suffix || ""; + parser.hooks.expression.for(name).tap("NodeSourcePlugin", () => { + if ( + parser.state.module && + parser.state.module.resource === getPathToModule(module, type) + ) + return; + const mockModule = ParserHelpers.requireFileAsExpression( + parser.state.module.context, + getPathToModule(module, type) + ); + return ParserHelpers.addParsedVariableToModule( + parser, + name, + mockModule + suffix + ); + }); + }; + + compiler.hooks.compilation.tap( + "NodeSourcePlugin", + (compilation, { normalModuleFactory }) => { + const handler = (parser, parserOptions) => { + if (parserOptions.node === false) return; + + let localOptions = options; + if (parserOptions.node) { + localOptions = Object.assign({}, localOptions, parserOptions.node); + } + if (localOptions.global) { + parser.hooks.expression + .for("global") + .tap("NodeSourcePlugin", () => { + const retrieveGlobalModule = ParserHelpers.requireFileAsExpression( + parser.state.module.context, + require.resolve("../../buildin/global") + ); + return ParserHelpers.addParsedVariableToModule( + parser, + "global", + retrieveGlobalModule + ); + }); + } + if (localOptions.process) { + const processType = localOptions.process; + addExpression(parser, "process", "process", processType); + } + if (localOptions.console) { + const consoleType = localOptions.console; + addExpression(parser, "console", "console", consoleType); + } + const bufferType = localOptions.Buffer; + if (bufferType) { + addExpression(parser, "Buffer", "buffer", bufferType, ".Buffer"); + } + if (localOptions.setImmediate) { + const setImmediateType = localOptions.setImmediate; + addExpression( + parser, + "setImmediate", + "timers", + setImmediateType, + ".setImmediate" + ); + addExpression( + parser, + "clearImmediate", + "timers", + setImmediateType, + ".clearImmediate" + ); + } + }; + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("NodeSourcePlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("NodeSourcePlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("NodeSourcePlugin", handler); + } + ); + compiler.hooks.afterResolvers.tap("NodeSourcePlugin", compiler => { + for (const lib of Object.keys(nodeLibsBrowser)) { + if (options[lib] !== false) { + compiler.resolverFactory.hooks.resolver + .for("normal") + .tap("NodeSourcePlugin", resolver => { + new AliasPlugin( + "described-resolve", + { + name: lib, + onlyModule: true, + alias: getPathToModule(lib, options[lib]) + }, + "resolve" + ).apply(resolver); + }); + } + } + }); + } +}; diff --git a/node_modules/webpack/lib/node/NodeTargetPlugin.js b/node_modules/webpack/lib/node/NodeTargetPlugin.js index 528a28570..b76b70690 100644 --- a/node_modules/webpack/lib/node/NodeTargetPlugin.js +++ b/node_modules/webpack/lib/node/NodeTargetPlugin.js @@ -1,15 +1,19 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const ExternalsPlugin = require("../ExternalsPlugin");
-
-class NodeTargetPlugin {
- apply(compiler) {
- new ExternalsPlugin("commonjs", Object.keys(process.binding("natives"))).apply(compiler);
- }
-}
-
-module.exports = NodeTargetPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const ExternalsPlugin = require("../ExternalsPlugin"); + +const builtins = + // eslint-disable-next-line node/no-unsupported-features/node-builtins + require("module").builtinModules || Object.keys(process.binding("natives")); + +class NodeTargetPlugin { + apply(compiler) { + new ExternalsPlugin("commonjs", builtins).apply(compiler); + } +} + +module.exports = NodeTargetPlugin; diff --git a/node_modules/webpack/lib/node/NodeTemplatePlugin.js b/node_modules/webpack/lib/node/NodeTemplatePlugin.js index ed17d1937..cdb1076b9 100644 --- a/node_modules/webpack/lib/node/NodeTemplatePlugin.js +++ b/node_modules/webpack/lib/node/NodeTemplatePlugin.js @@ -1,27 +1,31 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-
-"use strict";
-
-const NodeMainTemplatePlugin = require("./NodeMainTemplatePlugin");
-const NodeChunkTemplatePlugin = require("./NodeChunkTemplatePlugin");
-const NodeHotUpdateChunkTemplatePlugin = require("./NodeHotUpdateChunkTemplatePlugin");
-
-class NodeTemplatePlugin {
- constructor(options) {
- options = options || {};
- this.asyncChunkLoading = options.asyncChunkLoading;
- }
-
- apply(compiler) {
- compiler.plugin("this-compilation", (compilation) => {
- compilation.mainTemplate.apply(new NodeMainTemplatePlugin(this.asyncChunkLoading));
- compilation.chunkTemplate.apply(new NodeChunkTemplatePlugin());
- compilation.hotUpdateChunkTemplate.apply(new NodeHotUpdateChunkTemplatePlugin());
- });
- }
-}
-
-module.exports = NodeTemplatePlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const NodeMainTemplatePlugin = require("./NodeMainTemplatePlugin"); +const NodeChunkTemplatePlugin = require("./NodeChunkTemplatePlugin"); +const NodeHotUpdateChunkTemplatePlugin = require("./NodeHotUpdateChunkTemplatePlugin"); + +class NodeTemplatePlugin { + constructor(options) { + options = options || {}; + this.asyncChunkLoading = options.asyncChunkLoading; + } + + apply(compiler) { + compiler.hooks.thisCompilation.tap("NodeTemplatePlugin", compilation => { + new NodeMainTemplatePlugin(this.asyncChunkLoading).apply( + compilation.mainTemplate + ); + new NodeChunkTemplatePlugin().apply(compilation.chunkTemplate); + new NodeHotUpdateChunkTemplatePlugin().apply( + compilation.hotUpdateChunkTemplate + ); + }); + } +} + +module.exports = NodeTemplatePlugin; diff --git a/node_modules/webpack/lib/node/NodeWatchFileSystem.js b/node_modules/webpack/lib/node/NodeWatchFileSystem.js index 1c13a9b29..62d8532cd 100644 --- a/node_modules/webpack/lib/node/NodeWatchFileSystem.js +++ b/node_modules/webpack/lib/node/NodeWatchFileSystem.js @@ -1,72 +1,99 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const Watchpack = require("watchpack");
-
-class NodeWatchFileSystem {
- constructor(inputFileSystem) {
- this.inputFileSystem = inputFileSystem;
- this.watcherOptions = {
- aggregateTimeout: 0
- };
- this.watcher = new Watchpack(this.watcherOptions);
- }
-
- watch(files, dirs, missing, startTime, options, callback, callbackUndelayed) {
- if(!Array.isArray(files))
- throw new Error("Invalid arguments: 'files'");
- if(!Array.isArray(dirs))
- throw new Error("Invalid arguments: 'dirs'");
- if(!Array.isArray(missing))
- throw new Error("Invalid arguments: 'missing'");
- if(typeof callback !== "function")
- throw new Error("Invalid arguments: 'callback'");
- if(typeof startTime !== "number" && startTime)
- throw new Error("Invalid arguments: 'startTime'");
- if(typeof options !== "object")
- throw new Error("Invalid arguments: 'options'");
- if(typeof callbackUndelayed !== "function" && callbackUndelayed)
- throw new Error("Invalid arguments: 'callbackUndelayed'");
- const oldWatcher = this.watcher;
- this.watcher = new Watchpack(options);
-
- if(callbackUndelayed)
- this.watcher.once("change", callbackUndelayed);
-
- this.watcher.once("aggregated", (changes, removals) => {
- changes = changes.concat(removals);
- if(this.inputFileSystem && this.inputFileSystem.purge) {
- this.inputFileSystem.purge(changes);
- }
- const times = this.watcher.getTimes();
- callback(null,
- changes.filter(file => files.indexOf(file) >= 0).sort(),
- changes.filter(file => dirs.indexOf(file) >= 0).sort(),
- changes.filter(file => missing.indexOf(file) >= 0).sort(), times, times);
- });
-
- this.watcher.watch(files.concat(missing), dirs.concat(missing), startTime);
-
- if(oldWatcher) {
- oldWatcher.close();
- }
- return {
- close: () => {
- if(this.watcher) {
- this.watcher.close();
- this.watcher = null;
- }
- },
- pause: () => {
- if(this.watcher) {
- this.watcher.pause();
- }
- }
- };
- }
-}
-
-module.exports = NodeWatchFileSystem;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Watchpack = require("watchpack"); +const objectToMap = require("../util/objectToMap"); + +class NodeWatchFileSystem { + constructor(inputFileSystem) { + this.inputFileSystem = inputFileSystem; + this.watcherOptions = { + aggregateTimeout: 0 + }; + this.watcher = new Watchpack(this.watcherOptions); + } + + watch(files, dirs, missing, startTime, options, callback, callbackUndelayed) { + if (!Array.isArray(files)) { + throw new Error("Invalid arguments: 'files'"); + } + if (!Array.isArray(dirs)) { + throw new Error("Invalid arguments: 'dirs'"); + } + if (!Array.isArray(missing)) { + throw new Error("Invalid arguments: 'missing'"); + } + if (typeof callback !== "function") { + throw new Error("Invalid arguments: 'callback'"); + } + if (typeof startTime !== "number" && startTime) { + throw new Error("Invalid arguments: 'startTime'"); + } + if (typeof options !== "object") { + throw new Error("Invalid arguments: 'options'"); + } + if (typeof callbackUndelayed !== "function" && callbackUndelayed) { + throw new Error("Invalid arguments: 'callbackUndelayed'"); + } + const oldWatcher = this.watcher; + this.watcher = new Watchpack(options); + + if (callbackUndelayed) { + this.watcher.once("change", callbackUndelayed); + } + + this.watcher.once("aggregated", (changes, removals) => { + changes = changes.concat(removals); + if (this.inputFileSystem && this.inputFileSystem.purge) { + this.inputFileSystem.purge(changes); + } + const times = objectToMap(this.watcher.getTimes()); + callback( + null, + changes.filter(file => files.includes(file)).sort(), + changes.filter(file => dirs.includes(file)).sort(), + changes.filter(file => missing.includes(file)).sort(), + times, + times + ); + }); + + this.watcher.watch(files.concat(missing), dirs.concat(missing), startTime); + + if (oldWatcher) { + oldWatcher.close(); + } + return { + close: () => { + if (this.watcher) { + this.watcher.close(); + this.watcher = null; + } + }, + pause: () => { + if (this.watcher) { + this.watcher.pause(); + } + }, + getFileTimestamps: () => { + if (this.watcher) { + return objectToMap(this.watcher.getTimes()); + } else { + return new Map(); + } + }, + getContextTimestamps: () => { + if (this.watcher) { + return objectToMap(this.watcher.getTimes()); + } else { + return new Map(); + } + } + }; + } +} + +module.exports = NodeWatchFileSystem; diff --git a/node_modules/webpack/lib/optimize/AggressiveMergingPlugin.js b/node_modules/webpack/lib/optimize/AggressiveMergingPlugin.js index dc14ac300..e3a4c37ee 100644 --- a/node_modules/webpack/lib/optimize/AggressiveMergingPlugin.js +++ b/node_modules/webpack/lib/optimize/AggressiveMergingPlugin.js @@ -1,115 +1,87 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-class AggressiveMergingPlugin {
- constructor(options) {
- if(options !== undefined && typeof options !== "object" || Array.isArray(options)) {
- throw new Error("Argument should be an options object. To use defaults, pass in nothing.\nFor more info on options, see https://webpack.js.org/plugins/");
- }
- this.options = options || {};
- }
-
- apply(compiler) {
- const options = this.options;
- const minSizeReduce = options.minSizeReduce || 1.5;
-
- function getParentsWeight(chunk) {
- return chunk.parents.map((p) => {
- return p.isInitial() ? options.entryChunkMultiplicator || 10 : 1;
- }).reduce((a, b) => {
- return a + b;
- }, 0);
- }
- compiler.plugin("this-compilation", (compilation) => {
- compilation.plugin("optimize-chunks-advanced", (chunks) => {
- let combinations = [];
- chunks.forEach((a, idx) => {
- if(a.isInitial()) return;
- for(let i = 0; i < idx; i++) {
- const b = chunks[i];
- if(b.isInitial()) continue;
- combinations.push({
- a,
- b,
- improvement: undefined
- });
- }
- });
-
- combinations.forEach((pair) => {
- const a = pair.b.size({
- chunkOverhead: 0
- });
- const b = pair.a.size({
- chunkOverhead: 0
- });
- const ab = pair.b.integratedSize(pair.a, {
- chunkOverhead: 0
- });
- let newSize;
- if(ab === false) {
- pair.improvement = false;
- return;
- } else if(options.moveToParents) {
- const aOnly = ab - b;
- const bOnly = ab - a;
- const common = a + b - ab;
- newSize = common + getParentsWeight(pair.b) * aOnly + getParentsWeight(pair.a) * bOnly;
- } else {
- newSize = ab;
- }
-
- pair.improvement = (a + b) / newSize;
- });
- combinations = combinations.filter((pair) => {
- return pair.improvement !== false;
- });
- combinations.sort((a, b) => {
- return b.improvement - a.improvement;
- });
-
- const pair = combinations[0];
-
- if(!pair) return;
- if(pair.improvement < minSizeReduce) return;
-
- if(options.moveToParents) {
- const commonModules = pair.b.modules.filter((m) => {
- return pair.a.modules.indexOf(m) >= 0;
- });
- const aOnlyModules = pair.b.modules.filter((m) => {
- return commonModules.indexOf(m) < 0;
- });
- const bOnlyModules = pair.a.modules.filter((m) => {
- return commonModules.indexOf(m) < 0;
- });
- aOnlyModules.forEach((m) => {
- pair.b.removeModule(m);
- m.removeChunk(pair.b);
- pair.b.parents.forEach((c) => {
- c.addModule(m);
- m.addChunk(c);
- });
- });
- bOnlyModules.forEach((m) => {
- pair.a.removeModule(m);
- m.removeChunk(pair.a);
- pair.a.parents.forEach((c) => {
- c.addModule(m);
- m.addChunk(c);
- });
- });
- }
- if(pair.b.integrate(pair.a, "aggressive-merge")) {
- chunks.splice(chunks.indexOf(pair.a), 1);
- return true;
- }
- });
- });
- }
-}
-
-module.exports = AggressiveMergingPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +class AggressiveMergingPlugin { + constructor(options) { + if ( + (options !== undefined && typeof options !== "object") || + Array.isArray(options) + ) { + throw new Error( + "Argument should be an options object. To use defaults, pass in nothing.\nFor more info on options, see https://webpack.js.org/plugins/" + ); + } + this.options = options || {}; + } + + apply(compiler) { + const options = this.options; + const minSizeReduce = options.minSizeReduce || 1.5; + + compiler.hooks.thisCompilation.tap( + "AggressiveMergingPlugin", + compilation => { + compilation.hooks.optimizeChunksAdvanced.tap( + "AggressiveMergingPlugin", + chunks => { + let combinations = []; + chunks.forEach((a, idx) => { + if (a.canBeInitial()) return; + for (let i = 0; i < idx; i++) { + const b = chunks[i]; + if (b.canBeInitial()) continue; + combinations.push({ + a, + b, + improvement: undefined + }); + } + }); + + for (const pair of combinations) { + const a = pair.b.size({ + chunkOverhead: 0 + }); + const b = pair.a.size({ + chunkOverhead: 0 + }); + const ab = pair.b.integratedSize(pair.a, { + chunkOverhead: 0 + }); + let newSize; + if (ab === false) { + pair.improvement = false; + return; + } else { + newSize = ab; + } + + pair.improvement = (a + b) / newSize; + } + combinations = combinations.filter(pair => { + return pair.improvement !== false; + }); + combinations.sort((a, b) => { + return b.improvement - a.improvement; + }); + + const pair = combinations[0]; + + if (!pair) return; + if (pair.improvement < minSizeReduce) return; + + if (pair.b.integrate(pair.a, "aggressive-merge")) { + chunks.splice(chunks.indexOf(pair.a), 1); + return true; + } + } + ); + } + ); + } +} + +module.exports = AggressiveMergingPlugin; diff --git a/node_modules/webpack/lib/optimize/AggressiveSplittingPlugin.js b/node_modules/webpack/lib/optimize/AggressiveSplittingPlugin.js index b6f566a1c..9aec3644b 100644 --- a/node_modules/webpack/lib/optimize/AggressiveSplittingPlugin.js +++ b/node_modules/webpack/lib/optimize/AggressiveSplittingPlugin.js @@ -1,195 +1,287 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const identifierUtils = require("../util/identifier");
-
-function moveModuleBetween(oldChunk, newChunk) {
- return function(module) {
- oldChunk.moveModule(module, newChunk);
- };
-}
-
-function isNotAEntryModule(entryModule) {
- return function(module) {
- return entryModule !== module;
- };
-}
-
-function copyWithReason(obj) {
- const newObj = {};
- Object.keys(obj).forEach((key) => {
- newObj[key] = obj[key];
- });
- if(!newObj.reasons || newObj.reasons.indexOf("aggressive-splitted") < 0)
- newObj.reasons = (newObj.reasons || []).concat("aggressive-splitted");
- return newObj;
-}
-
-class AggressiveSplittingPlugin {
- constructor(options) {
- this.options = options || {};
- if(typeof this.options.minSize !== "number") this.options.minSize = 30 * 1024;
- if(typeof this.options.maxSize !== "number") this.options.maxSize = 50 * 1024;
- if(typeof this.options.chunkOverhead !== "number") this.options.chunkOverhead = 0;
- if(typeof this.options.entryChunkMultiplicator !== "number") this.options.entryChunkMultiplicator = 1;
- }
- apply(compiler) {
- compiler.plugin("this-compilation", (compilation) => {
- compilation.plugin("optimize-chunks-advanced", (chunks) => {
- // Precompute stuff
- const nameToModuleMap = new Map();
- compilation.modules.forEach(m => {
- const name = identifierUtils.makePathsRelative(compiler.context, m.identifier(), compilation.cache);
- nameToModuleMap.set(name, m);
- });
-
- const savedSplits = compilation.records && compilation.records.aggressiveSplits || [];
- const usedSplits = compilation._aggressiveSplittingSplits ?
- savedSplits.concat(compilation._aggressiveSplittingSplits) : savedSplits;
-
- const minSize = this.options.minSize;
- const maxSize = this.options.maxSize;
- // 1. try to restore to recorded splitting
- for(let j = 0; j < usedSplits.length; j++) {
- const splitData = usedSplits[j];
- const selectedModules = splitData.modules.map(name => nameToModuleMap.get(name));
-
- // Does the modules exist at all?
- if(selectedModules.every(Boolean)) {
-
- // Find all chunks containing all modules in the split
- for(let i = 0; i < chunks.length; i++) {
- const chunk = chunks[i];
-
- // Cheap check if chunk is suitable at all
- if(chunk.getNumberOfModules() < splitData.modules.length)
- continue;
-
- // Check if all modules are in the chunk
- if(selectedModules.every(m => chunk.containsModule(m))) {
-
- // Is chunk identical to the split or do we need to split it?
- if(chunk.getNumberOfModules() > splitData.modules.length) {
- // split the chunk into two parts
- const newChunk = compilation.addChunk();
- selectedModules.forEach(moveModuleBetween(chunk, newChunk));
- chunk.split(newChunk);
- chunk.name = null;
- newChunk._fromAggressiveSplitting = true;
- if(j < savedSplits.length)
- newChunk._fromAggressiveSplittingIndex = j;
- if(splitData.id !== null && splitData.id !== undefined) {
- newChunk.id = splitData.id;
- }
- newChunk.origins = chunk.origins.map(copyWithReason);
- chunk.origins = chunk.origins.map(copyWithReason);
- return true;
- } else { // chunk is identical to the split
- if(j < savedSplits.length)
- chunk._fromAggressiveSplittingIndex = j;
- chunk.name = null;
- if(splitData.id !== null && splitData.id !== undefined) {
- chunk.id = splitData.id;
- }
- }
- }
- }
- }
- }
-
- // 2. for any other chunk which isn't splitted yet, split it
- for(let i = 0; i < chunks.length; i++) {
- const chunk = chunks[i];
- const size = chunk.size(this.options);
- if(size > maxSize && chunk.getNumberOfModules() > 1) {
- const newChunk = compilation.addChunk();
- const modules = chunk.getModules()
- .filter(isNotAEntryModule(chunk.entryModule))
- .sort((a, b) => {
- a = a.identifier();
- b = b.identifier();
- if(a > b) return 1;
- if(a < b) return -1;
- return 0;
- });
- for(let k = 0; k < modules.length; k++) {
- chunk.moveModule(modules[k], newChunk);
- const newSize = newChunk.size(this.options);
- const chunkSize = chunk.size(this.options);
- // break early if it's fine
- if(chunkSize < maxSize && newSize < maxSize && newSize >= minSize && chunkSize >= minSize)
- break;
- if(newSize > maxSize && k === 0) {
- // break if there is a single module which is bigger than maxSize
- break;
- }
- if(newSize > maxSize || chunkSize < minSize) {
- // move it back
- newChunk.moveModule(modules[k], chunk);
- // check if it's fine now
- if(newSize < maxSize && newSize >= minSize && chunkSize >= minSize)
- break;
- }
- }
- if(newChunk.getNumberOfModules() > 0) {
- chunk.split(newChunk);
- chunk.name = null;
- newChunk.origins = chunk.origins.map(copyWithReason);
- chunk.origins = chunk.origins.map(copyWithReason);
- compilation._aggressiveSplittingSplits = (compilation._aggressiveSplittingSplits || []).concat({
- modules: newChunk.mapModules(m => identifierUtils.makePathsRelative(compiler.context, m.identifier(), compilation.cache))
- });
- return true;
- } else {
- chunks.splice(chunks.indexOf(newChunk), 1);
- }
- }
- }
- });
- compilation.plugin("record-hash", (records) => {
- // 3. save to made splittings to records
- const minSize = this.options.minSize;
- if(!records.aggressiveSplits) records.aggressiveSplits = [];
- compilation.chunks.forEach((chunk) => {
- if(chunk.hasEntryModule()) return;
- const size = chunk.size(this.options);
- const incorrectSize = size < minSize;
- const modules = chunk.mapModules(m => identifierUtils.makePathsRelative(compiler.context, m.identifier(), compilation.cache));
- if(typeof chunk._fromAggressiveSplittingIndex === "undefined") {
- if(incorrectSize) return;
- chunk.recorded = true;
- records.aggressiveSplits.push({
- modules: modules,
- hash: chunk.hash,
- id: chunk.id
- });
- } else {
- const splitData = records.aggressiveSplits[chunk._fromAggressiveSplittingIndex];
- if(splitData.hash !== chunk.hash || incorrectSize) {
- if(chunk._fromAggressiveSplitting) {
- chunk._aggressiveSplittingInvalid = true;
- splitData.invalid = true;
- } else {
- splitData.hash = chunk.hash;
- }
- }
- }
- });
- records.aggressiveSplits = records.aggressiveSplits.filter((splitData) => {
- return !splitData.invalid;
- });
- });
- compilation.plugin("need-additional-seal", (callback) => {
- const invalid = compilation.chunks.some((chunk) => {
- return chunk._aggressiveSplittingInvalid;
- });
- if(invalid)
- return true;
- });
- });
- }
-}
-module.exports = AggressiveSplittingPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const identifierUtils = require("../util/identifier"); +const { intersect } = require("../util/SetHelpers"); +const validateOptions = require("schema-utils"); +const schema = require("../../schemas/plugins/optimize/AggressiveSplittingPlugin.json"); + +const moveModuleBetween = (oldChunk, newChunk) => { + return module => { + oldChunk.moveModule(module, newChunk); + }; +}; + +const isNotAEntryModule = entryModule => { + return module => { + return entryModule !== module; + }; +}; + +class AggressiveSplittingPlugin { + constructor(options) { + validateOptions(schema, options || {}, "Aggressive Splitting Plugin"); + + this.options = options || {}; + if (typeof this.options.minSize !== "number") { + this.options.minSize = 30 * 1024; + } + if (typeof this.options.maxSize !== "number") { + this.options.maxSize = 50 * 1024; + } + if (typeof this.options.chunkOverhead !== "number") { + this.options.chunkOverhead = 0; + } + if (typeof this.options.entryChunkMultiplicator !== "number") { + this.options.entryChunkMultiplicator = 1; + } + } + apply(compiler) { + compiler.hooks.thisCompilation.tap( + "AggressiveSplittingPlugin", + compilation => { + let needAdditionalSeal = false; + let newSplits; + let fromAggressiveSplittingSet; + let chunkSplitDataMap; + compilation.hooks.optimize.tap("AggressiveSplittingPlugin", () => { + newSplits = []; + fromAggressiveSplittingSet = new Set(); + chunkSplitDataMap = new Map(); + }); + compilation.hooks.optimizeChunksAdvanced.tap( + "AggressiveSplittingPlugin", + chunks => { + // Precompute stuff + const nameToModuleMap = new Map(); + const moduleToNameMap = new Map(); + for (const m of compilation.modules) { + const name = identifierUtils.makePathsRelative( + compiler.context, + m.identifier(), + compilation.cache + ); + nameToModuleMap.set(name, m); + moduleToNameMap.set(m, name); + } + + // Check used chunk ids + const usedIds = new Set(); + for (const chunk of chunks) { + usedIds.add(chunk.id); + } + + const recordedSplits = + (compilation.records && compilation.records.aggressiveSplits) || + []; + const usedSplits = newSplits + ? recordedSplits.concat(newSplits) + : recordedSplits; + + const minSize = this.options.minSize; + const maxSize = this.options.maxSize; + + const applySplit = splitData => { + // Cannot split if id is already taken + if (splitData.id !== undefined && usedIds.has(splitData.id)) { + return false; + } + + // Get module objects from names + const selectedModules = splitData.modules.map(name => + nameToModuleMap.get(name) + ); + + // Does the modules exist at all? + if (!selectedModules.every(Boolean)) return false; + + // Check if size matches (faster than waiting for hash) + const size = selectedModules.reduce( + (sum, m) => sum + m.size(), + 0 + ); + if (size !== splitData.size) return false; + + // get chunks with all modules + const selectedChunks = intersect( + selectedModules.map(m => new Set(m.chunksIterable)) + ); + + // No relevant chunks found + if (selectedChunks.size === 0) return false; + + // The found chunk is already the split or similar + if ( + selectedChunks.size === 1 && + Array.from(selectedChunks)[0].getNumberOfModules() === + selectedModules.length + ) { + const chunk = Array.from(selectedChunks)[0]; + if (fromAggressiveSplittingSet.has(chunk)) return false; + fromAggressiveSplittingSet.add(chunk); + chunkSplitDataMap.set(chunk, splitData); + return true; + } + + // split the chunk into two parts + const newChunk = compilation.addChunk(); + newChunk.chunkReason = "aggressive splitted"; + for (const chunk of selectedChunks) { + selectedModules.forEach(moveModuleBetween(chunk, newChunk)); + chunk.split(newChunk); + chunk.name = null; + } + fromAggressiveSplittingSet.add(newChunk); + chunkSplitDataMap.set(newChunk, splitData); + + if (splitData.id !== null && splitData.id !== undefined) { + newChunk.id = splitData.id; + } + return true; + }; + + // try to restore to recorded splitting + let changed = false; + for (let j = 0; j < usedSplits.length; j++) { + const splitData = usedSplits[j]; + if (applySplit(splitData)) changed = true; + } + + // for any chunk which isn't splitted yet, split it and create a new entry + // start with the biggest chunk + const sortedChunks = chunks.slice().sort((a, b) => { + const diff1 = b.modulesSize() - a.modulesSize(); + if (diff1) return diff1; + const diff2 = a.getNumberOfModules() - b.getNumberOfModules(); + if (diff2) return diff2; + const modulesA = Array.from(a.modulesIterable); + const modulesB = Array.from(b.modulesIterable); + modulesA.sort(); + modulesB.sort(); + const aI = modulesA[Symbol.iterator](); + const bI = modulesB[Symbol.iterator](); + // eslint-disable-next-line no-constant-condition + while (true) { + const aItem = aI.next(); + const bItem = bI.next(); + if (aItem.done) return 0; + const aModuleIdentifier = aItem.value.identifier(); + const bModuleIdentifier = bItem.value.identifier(); + if (aModuleIdentifier > bModuleIdentifier) return -1; + if (aModuleIdentifier < bModuleIdentifier) return 1; + } + }); + for (const chunk of sortedChunks) { + if (fromAggressiveSplittingSet.has(chunk)) continue; + const size = chunk.modulesSize(); + if (size > maxSize && chunk.getNumberOfModules() > 1) { + const modules = chunk + .getModules() + .filter(isNotAEntryModule(chunk.entryModule)) + .sort((a, b) => { + a = a.identifier(); + b = b.identifier(); + if (a > b) return 1; + if (a < b) return -1; + return 0; + }); + const selectedModules = []; + let selectedModulesSize = 0; + for (let k = 0; k < modules.length; k++) { + const module = modules[k]; + const newSize = selectedModulesSize + module.size(); + if (newSize > maxSize && selectedModulesSize >= minSize) { + break; + } + selectedModulesSize = newSize; + selectedModules.push(module); + } + if (selectedModules.length === 0) continue; + const splitData = { + modules: selectedModules + .map(m => moduleToNameMap.get(m)) + .sort(), + size: selectedModulesSize + }; + + if (applySplit(splitData)) { + newSplits = (newSplits || []).concat(splitData); + changed = true; + } + } + } + if (changed) return true; + } + ); + compilation.hooks.recordHash.tap( + "AggressiveSplittingPlugin", + records => { + // 4. save made splittings to records + const allSplits = new Set(); + const invalidSplits = new Set(); + + // Check if some splittings are invalid + // We remove invalid splittings and try again + for (const chunk of compilation.chunks) { + const splitData = chunkSplitDataMap.get(chunk); + if (splitData !== undefined) { + if (splitData.hash && chunk.hash !== splitData.hash) { + // Split was successful, but hash doesn't equal + // We can throw away the split since it's useless now + invalidSplits.add(splitData); + } + } + } + + if (invalidSplits.size > 0) { + records.aggressiveSplits = records.aggressiveSplits.filter( + splitData => !invalidSplits.has(splitData) + ); + needAdditionalSeal = true; + } else { + // set hash and id values on all (new) splittings + for (const chunk of compilation.chunks) { + const splitData = chunkSplitDataMap.get(chunk); + if (splitData !== undefined) { + splitData.hash = chunk.hash; + splitData.id = chunk.id; + allSplits.add(splitData); + // set flag for stats + chunk.recorded = true; + } + } + + // Also add all unused historial splits (after the used ones) + // They can still be used in some future compilation + const recordedSplits = + compilation.records && compilation.records.aggressiveSplits; + if (recordedSplits) { + for (const splitData of recordedSplits) { + if (!invalidSplits.has(splitData)) allSplits.add(splitData); + } + } + + // record all splits + records.aggressiveSplits = Array.from(allSplits); + + needAdditionalSeal = false; + } + } + ); + compilation.hooks.needAdditionalSeal.tap( + "AggressiveSplittingPlugin", + () => { + if (needAdditionalSeal) { + needAdditionalSeal = false; + return true; + } + } + ); + } + ); + } +} +module.exports = AggressiveSplittingPlugin; diff --git a/node_modules/webpack/lib/optimize/ChunkModuleIdRangePlugin.js b/node_modules/webpack/lib/optimize/ChunkModuleIdRangePlugin.js index 262014dc5..f507e426c 100644 --- a/node_modules/webpack/lib/optimize/ChunkModuleIdRangePlugin.js +++ b/node_modules/webpack/lib/optimize/ChunkModuleIdRangePlugin.js @@ -1,53 +1,68 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-class ChunkModuleIdRangePlugin {
- constructor(options) {
- this.options = options;
- }
- apply(compiler) {
- const options = this.options;
- compiler.plugin("compilation", (compilation) => {
- compilation.plugin("module-ids", (modules) => {
- const chunk = this.chunks.find((chunk) => chunk.name === options.name);
- if(!chunk) throw new Error("ChunkModuleIdRangePlugin: Chunk with name '" + options.name + "' was not found");
- let currentId = options.start;
- let chunkModules;
- if(options.order) {
- chunkModules = chunk.modules.slice();
- switch(options.order) {
- case "index":
- chunkModules.sort((a, b) => {
- return a.index - b.index;
- });
- break;
- case "index2":
- chunkModules.sort((a, b) => {
- return a.index2 - b.index2;
- });
- break;
- default:
- throw new Error("ChunkModuleIdRangePlugin: unexpected value of order");
- }
-
- } else {
- chunkModules = modules.filter((m) => {
- return m.chunks.indexOf(chunk) >= 0;
- });
- }
-
- for(let i = 0; i < chunkModules.length; i++) {
- const m = chunkModules[i];
- if(m.id === null) {
- m.id = currentId++;
- }
- if(options.end && currentId > options.end)
- break;
- }
- });
- });
- }
-}
-module.exports = ChunkModuleIdRangePlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const sortByIndex = (a, b) => { + return a.index - b.index; +}; + +const sortByIndex2 = (a, b) => { + return a.index2 - b.index2; +}; + +class ChunkModuleIdRangePlugin { + constructor(options) { + this.options = options; + } + + apply(compiler) { + const options = this.options; + compiler.hooks.compilation.tap("ChunkModuleIdRangePlugin", compilation => { + compilation.hooks.moduleIds.tap("ChunkModuleIdRangePlugin", modules => { + const chunk = compilation.chunks.find( + chunk => chunk.name === options.name + ); + if (!chunk) { + throw new Error( + `ChunkModuleIdRangePlugin: Chunk with name '${ + options.name + }"' was not found` + ); + } + + let chunkModules; + if (options.order) { + chunkModules = Array.from(chunk.modulesIterable); + switch (options.order) { + case "index": + chunkModules.sort(sortByIndex); + break; + case "index2": + chunkModules.sort(sortByIndex2); + break; + default: + throw new Error( + "ChunkModuleIdRangePlugin: unexpected value of order" + ); + } + } else { + chunkModules = modules.filter(m => { + return m.chunksIterable.has(chunk); + }); + } + + let currentId = options.start || 0; + for (let i = 0; i < chunkModules.length; i++) { + const m = chunkModules[i]; + if (m.id === null) { + m.id = currentId++; + } + if (options.end && currentId > options.end) break; + } + }); + }); + } +} +module.exports = ChunkModuleIdRangePlugin; diff --git a/node_modules/webpack/lib/optimize/CommonsChunkPlugin.js b/node_modules/webpack/lib/optimize/CommonsChunkPlugin.js deleted file mode 100644 index c0e438a40..000000000 --- a/node_modules/webpack/lib/optimize/CommonsChunkPlugin.js +++ /dev/null @@ -1,404 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-let nextIdent = 0;
-
-class CommonsChunkPlugin {
- constructor(options) {
- if(arguments.length > 1) {
- throw new Error(`Deprecation notice: CommonsChunkPlugin now only takes a single argument. Either an options
-object *or* the name of the chunk.
-Example: if your old code looked like this:
- new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.bundle.js')
-You would change it to:
- new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.bundle.js' })
-The available options are:
- name: string
- names: string[]
- filename: string
- minChunks: number
- chunks: string[]
- children: boolean
- async: boolean
- minSize: number`);
- }
-
- const normalizedOptions = this.normalizeOptions(options);
-
- this.chunkNames = normalizedOptions.chunkNames;
- this.filenameTemplate = normalizedOptions.filenameTemplate;
- this.minChunks = normalizedOptions.minChunks;
- this.selectedChunks = normalizedOptions.selectedChunks;
- this.children = normalizedOptions.children;
- this.deepChildren = normalizedOptions.deepChildren;
- this.async = normalizedOptions.async;
- this.minSize = normalizedOptions.minSize;
- this.ident = __filename + (nextIdent++);
- }
-
- normalizeOptions(options) {
- if(Array.isArray(options)) {
- return {
- chunkNames: options,
- };
- }
-
- if(typeof options === "string") {
- return {
- chunkNames: [options],
- };
- }
-
- // options.children and options.chunk may not be used together
- if(options.children && options.chunks) {
- throw new Error("You can't and it does not make any sense to use \"children\" and \"chunk\" options together.");
- }
-
- /**
- * options.async and options.filename are also not possible together
- * as filename specifies how the chunk is called but "async" implies
- * that webpack will take care of loading this file.
- */
- if(options.async && options.filename) {
- throw new Error(`You can not specify a filename if you use the "async" option.
-You can however specify the name of the async chunk by passing the desired string as the "async" option.`);
- }
-
- /**
- * Make sure this is either an array or undefined.
- * "name" can be a string and
- * "names" a string or an array
- */
- const chunkNames = options.name || options.names ? [].concat(options.name || options.names) : undefined;
- return {
- chunkNames: chunkNames,
- filenameTemplate: options.filename,
- minChunks: options.minChunks,
- selectedChunks: options.chunks,
- children: options.children,
- deepChildren: options.deepChildren,
- async: options.async,
- minSize: options.minSize
- };
- }
-
- apply(compiler) {
- compiler.plugin("this-compilation", (compilation) => {
- compilation.plugin(["optimize-chunks", "optimize-extracted-chunks"], (chunks) => {
- // only optimize once
- if(compilation[this.ident]) return;
- compilation[this.ident] = true;
-
- /**
- * Creates a list of "common"" chunks based on the options.
- * The list is made up of preexisting or newly created chunks.
- * - If chunk has the name as specified in the chunkNames it is put in the list
- * - If no chunk with the name as given in chunkNames exists a new chunk is created and added to the list
- *
- * These chunks are the "targets" for extracted modules.
- */
- const targetChunks = this.getTargetChunks(chunks, compilation, this.chunkNames, this.children, this.async);
-
- // iterate over all our new chunks
- targetChunks.forEach((targetChunk, idx) => {
-
- /**
- * These chunks are subject to get "common" modules extracted and moved to the common chunk
- */
- const affectedChunks = this.getAffectedChunks(compilation, chunks, targetChunk, targetChunks, idx, this.selectedChunks, this.async, this.children, this.deepChildren);
-
- // bail if no chunk is affected
- if(!affectedChunks) {
- return;
- }
-
- // If we are async create an async chunk now
- // override the "commonChunk" with the newly created async one and use it as commonChunk from now on
- let asyncChunk;
- if(this.async) {
- // If async chunk is one of the affected chunks, just use it
- asyncChunk = affectedChunks.filter(c => c.name === this.async)[0];
- // Elsewise create a new one
- if(!asyncChunk) {
- asyncChunk = this.createAsyncChunk(
- compilation,
- targetChunks.length <= 1 || typeof this.async !== "string" ? this.async :
- targetChunk.name ? `${this.async}-${targetChunk.name}` :
- true,
- targetChunk
- );
- }
- targetChunk = asyncChunk;
- }
-
- /**
- * Check which modules are "common" and could be extracted to a "common" chunk
- */
- const extractableModules = this.getExtractableModules(this.minChunks, affectedChunks, targetChunk);
-
- // If the minSize option is set check if the size extracted from the chunk is reached
- // else bail out here.
- // As all modules/commons are interlinked with each other, common modules would be extracted
- // if we reach this mark at a later common chunk. (quirky I guess).
- if(this.minSize) {
- const modulesSize = this.calculateModulesSize(extractableModules);
- // if too small, bail
- if(modulesSize < this.minSize)
- return;
- }
-
- // Remove modules that are moved to commons chunk from their original chunks
- // return all chunks that are affected by having modules removed - we need them later (apparently)
- const chunksWithExtractedModules = this.extractModulesAndReturnAffectedChunks(extractableModules, affectedChunks);
-
- // connect all extracted modules with the common chunk
- this.addExtractedModulesToTargetChunk(targetChunk, extractableModules);
-
- // set filenameTemplate for chunk
- if(this.filenameTemplate)
- targetChunk.filenameTemplate = this.filenameTemplate;
-
- // if we are async connect the blocks of the "reallyUsedChunk" - the ones that had modules removed -
- // with the commonChunk and get the origins for the asyncChunk (remember "asyncChunk === commonChunk" at this moment).
- // bail out
- if(this.async) {
- this.moveExtractedChunkBlocksToTargetChunk(chunksWithExtractedModules, targetChunk);
- asyncChunk.origins = this.extractOriginsOfChunksWithExtractedModules(chunksWithExtractedModules);
- return;
- }
-
- // we are not in "async" mode
- // connect used chunks with commonChunk - shouldnt this be reallyUsedChunks here?
- this.makeTargetChunkParentOfAffectedChunks(affectedChunks, targetChunk);
- });
- return true;
- });
- });
- }
-
- getTargetChunks(allChunks, compilation, chunkNames, children, asyncOption) {
- const asyncOrNoSelectedChunk = children || asyncOption;
-
- // we have specified chunk names
- if(chunkNames) {
- // map chunks by chunkName for quick access
- const allChunksNameMap = allChunks.reduce((map, chunk) => {
- if(chunk.name) {
- map.set(chunk.name, chunk);
- }
- return map;
- }, new Map());
-
- // Ensure we have a chunk per specified chunk name.
- // Reuse existing chunks if possible
- return chunkNames.map(chunkName => {
- if(allChunksNameMap.has(chunkName)) {
- return allChunksNameMap.get(chunkName);
- }
- // add the filtered chunks to the compilation
- return compilation.addChunk(chunkName);
- });
- }
-
- // we dont have named chunks specified, so we just take all of them
- if(asyncOrNoSelectedChunk) {
- return allChunks;
- }
-
- /**
- * No chunk name(s) was specified nor is this an async/children commons chunk
- */
- throw new Error(`You did not specify any valid target chunk settings.
-Take a look at the "name"/"names" or async/children option.`);
- }
-
- getAffectedUnnamedChunks(affectedChunks, targetChunk, rootChunk, asyncOption, deepChildrenOption) {
- let chunks = targetChunk.chunks;
- chunks && chunks.forEach((chunk) => {
- if(chunk.isInitial()) {
- return;
- }
- // If all the parents of a chunk are either
- // a) the target chunk we started with
- // b) themselves affected chunks
- // we can assume that this chunk is an affected chunk too, as there is no way a chunk that
- // isn't only depending on the target chunk is a parent of the chunk tested
- if(asyncOption || chunk.parents.every((parentChunk) => parentChunk === rootChunk || affectedChunks.has(parentChunk))) {
- // This check not only dedupes the affectedChunks but also guarantees we avoid endless loops
- if(!affectedChunks.has(chunk)) {
- // We mutate the affected chunks before going deeper, so the deeper levels and other branches
- // have the information of this chunk being affected for their assertion if a chunk should
- // not be affected
- affectedChunks.add(chunk);
-
- // We recurse down to all the children of the chunk, applying the same assumption.
- // This guarantees that if a chunk should be an affected chunk,
- // at the latest the last connection to the same chunk meets the
- // condition to add it to the affected chunks.
- if(deepChildrenOption === true) {
- this.getAffectedUnnamedChunks(affectedChunks, chunk, rootChunk, asyncOption, deepChildrenOption);
- }
- }
- }
- });
- }
-
- getAffectedChunks(compilation, allChunks, targetChunk, targetChunks, currentIndex, selectedChunks, asyncOption, childrenOption, deepChildrenOption) {
- const asyncOrNoSelectedChunk = childrenOption || asyncOption;
-
- if(Array.isArray(selectedChunks)) {
- return allChunks.filter(chunk => {
- const notCommmonChunk = chunk !== targetChunk;
- const isSelectedChunk = selectedChunks.indexOf(chunk.name) > -1;
- return notCommmonChunk && isSelectedChunk;
- });
- }
-
- if(asyncOrNoSelectedChunk) {
- let affectedChunks = new Set();
- this.getAffectedUnnamedChunks(affectedChunks, targetChunk, targetChunk, asyncOption, deepChildrenOption);
- return Array.from(affectedChunks);
- }
-
- /**
- * past this point only entry chunks are allowed to become commonChunks
- */
- if(targetChunk.parents.length > 0) {
- compilation.errors.push(new Error("CommonsChunkPlugin: While running in normal mode it's not allowed to use a non-entry chunk (" + targetChunk.name + ")"));
- return;
- }
-
- /**
- * If we find a "targetchunk" that is also a normal chunk (meaning it is probably specified as an entry)
- * and the current target chunk comes after that and the found chunk has a runtime*
- * make that chunk be an 'affected' chunk of the current target chunk.
- *
- * To understand what that means take a look at the "examples/chunkhash", this basically will
- * result in the runtime to be extracted to the current target chunk.
- *
- * *runtime: the "runtime" is the "webpack"-block you may have seen in the bundles that resolves modules etc.
- */
- return allChunks.filter((chunk) => {
- const found = targetChunks.indexOf(chunk);
- if(found >= currentIndex) return false;
- return chunk.hasRuntime();
- });
- }
-
- createAsyncChunk(compilation, asyncOption, targetChunk) {
- const asyncChunk = compilation.addChunk(typeof asyncOption === "string" ? asyncOption : undefined);
- asyncChunk.chunkReason = "async commons chunk";
- asyncChunk.extraAsync = true;
- asyncChunk.addParent(targetChunk);
- targetChunk.addChunk(asyncChunk);
- return asyncChunk;
- }
-
- // If minChunks is a function use that
- // otherwhise check if a module is used at least minChunks or 2 or usedChunks.length time
- getModuleFilter(minChunks, targetChunk, usedChunksLength) {
- if(typeof minChunks === "function") {
- return minChunks;
- }
- const minCount = (minChunks || Math.max(2, usedChunksLength));
- const isUsedAtLeastMinTimes = (module, count) => count >= minCount;
- return isUsedAtLeastMinTimes;
- }
-
- getExtractableModules(minChunks, usedChunks, targetChunk) {
- if(minChunks === Infinity) {
- return [];
- }
-
- // count how many chunks contain a module
- const commonModulesToCountMap = usedChunks.reduce((map, chunk) => {
- for(const module of chunk.modulesIterable) {
- const count = map.has(module) ? map.get(module) : 0;
- map.set(module, count + 1);
- }
- return map;
- }, new Map());
-
- // filter by minChunks
- const moduleFilterCount = this.getModuleFilter(minChunks, targetChunk, usedChunks.length);
- // filter by condition
- const moduleFilterCondition = (module, chunk) => {
- if(!module.chunkCondition) {
- return true;
- }
- return module.chunkCondition(chunk);
- };
-
- return Array.from(commonModulesToCountMap).filter(entry => {
- const module = entry[0];
- const count = entry[1];
- // if the module passes both filters, keep it.
- return moduleFilterCount(module, count) && moduleFilterCondition(module, targetChunk);
- }).map(entry => entry[0]);
- }
-
- calculateModulesSize(modules) {
- return modules.reduce((totalSize, module) => totalSize + module.size(), 0);
- }
-
- extractModulesAndReturnAffectedChunks(reallyUsedModules, usedChunks) {
- return reallyUsedModules.reduce((affectedChunksSet, module) => {
- for(const chunk of usedChunks) {
- // removeChunk returns true if the chunk was contained and succesfully removed
- // false if the module did not have a connection to the chunk in question
- if(module.removeChunk(chunk)) {
- affectedChunksSet.add(chunk);
- }
- }
- return affectedChunksSet;
- }, new Set());
- }
-
- addExtractedModulesToTargetChunk(chunk, modules) {
- for(const module of modules) {
- chunk.addModule(module);
- module.addChunk(chunk);
- }
- }
-
- makeTargetChunkParentOfAffectedChunks(usedChunks, commonChunk) {
- for(const chunk of usedChunks) {
- // set commonChunk as new sole parent
- chunk.parents = [commonChunk];
- // add chunk to commonChunk
- commonChunk.addChunk(chunk);
-
- for(const entrypoint of chunk.entrypoints) {
- entrypoint.insertChunk(commonChunk, chunk);
- }
- }
- }
-
- moveExtractedChunkBlocksToTargetChunk(chunks, targetChunk) {
- for(const chunk of chunks) {
- if(chunk === targetChunk) continue;
- for(const block of chunk.blocks) {
- if(block.chunks.indexOf(targetChunk) === -1) {
- block.chunks.unshift(targetChunk);
- }
- targetChunk.addBlock(block);
- }
- }
- }
-
- extractOriginsOfChunksWithExtractedModules(chunks) {
- const origins = [];
- for(const chunk of chunks) {
- for(const origin of chunk.origins) {
- const newOrigin = Object.create(origin);
- newOrigin.reasons = (origin.reasons || []).concat("async commons");
- origins.push(newOrigin);
- }
- }
- return origins;
- }
-}
-
-module.exports = CommonsChunkPlugin;
diff --git a/node_modules/webpack/lib/optimize/ConcatenatedModule.js b/node_modules/webpack/lib/optimize/ConcatenatedModule.js index bfb772496..52d33e6f3 100644 --- a/node_modules/webpack/lib/optimize/ConcatenatedModule.js +++ b/node_modules/webpack/lib/optimize/ConcatenatedModule.js @@ -1,827 +1,1495 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const Module = require("../Module");
-const Template = require("../Template");
-const Parser = require("../Parser");
-const crypto = require("crypto");
-const acorn = require("acorn");
-const escope = require("escope");
-const ReplaceSource = require("webpack-sources/lib/ReplaceSource");
-const ConcatSource = require("webpack-sources/lib/ConcatSource");
-const HarmonyImportDependency = require("../dependencies/HarmonyImportDependency");
-const HarmonyImportSpecifierDependency = require("../dependencies/HarmonyImportSpecifierDependency");
-const HarmonyExportSpecifierDependency = require("../dependencies/HarmonyExportSpecifierDependency");
-const HarmonyExportExpressionDependency = require("../dependencies/HarmonyExportExpressionDependency");
-const HarmonyExportImportedSpecifierDependency = require("../dependencies/HarmonyExportImportedSpecifierDependency");
-const HarmonyCompatibilityDependency = require("../dependencies/HarmonyCompatibilityDependency");
-
-function ensureNsObjSource(info, moduleToInfoMap, requestShortener) {
- if(!info.hasNamespaceObject) {
- info.hasNamespaceObject = true;
- const name = info.exportMap.get(true);
- const nsObj = [`var ${name} = {};`];
- for(const exportName of info.module.providedExports) {
- const finalName = getFinalName(info, exportName, moduleToInfoMap, requestShortener, false);
- nsObj.push(`__webpack_require__.d(${name}, ${JSON.stringify(exportName)}, function() { return ${finalName}; });`);
- }
- info.namespaceObjectSource = nsObj.join("\n") + "\n";
- }
-}
-
-function getExternalImport(importedModule, info, exportName, asCall) {
- if(exportName === true) return info.name;
- const used = importedModule.isUsed(exportName);
- if(!used) return "/* unused reexport */undefined";
- if(info.interop && exportName === "default") {
- return asCall ? `${info.interopName}()` : `${info.interopName}.a`;
- }
- // TODO use Template.toNormalComment when merging with pure-module
- const comment = used !== exportName ? ` /* ${exportName} */` : "";
- const reference = `${info.name}[${JSON.stringify(used)}${comment}]`;
- if(asCall)
- return `Object(${reference})`;
- return reference;
-}
-
-function getFinalName(info, exportName, moduleToInfoMap, requestShortener, asCall) {
- switch(info.type) {
- case "concatenated":
- {
- const directExport = info.exportMap.get(exportName);
- if(directExport) {
- if(exportName === true)
- ensureNsObjSource(info, moduleToInfoMap, requestShortener);
- const name = info.internalNames.get(directExport);
- if(!name)
- throw new Error(`The export "${directExport}" in "${info.module.readableIdentifier(requestShortener)}" has no internal name`);
- return name;
- }
- const reexport = info.reexportMap.get(exportName);
- if(reexport) {
- const refInfo = moduleToInfoMap.get(reexport.module);
- if(refInfo) {
- // module is in the concatenation
- return getFinalName(refInfo, reexport.exportName, moduleToInfoMap, requestShortener, asCall);
- }
- }
- const problem = `Cannot get final name for export "${exportName}" in "${info.module.readableIdentifier(requestShortener)}"` +
- ` (known exports: ${Array.from(info.exportMap.keys()).filter(name => name !== true).join(" ")}, ` +
- `known reexports: ${Array.from(info.reexportMap.keys()).join(" ")})`;
- // TODO use Template.toNormalComment when merging with pure-module
- return `/* ${problem} */ undefined`;
- }
- case "external":
- {
- const importedModule = info.module;
- return getExternalImport(importedModule, info, exportName, asCall);
- }
- }
-}
-
-function getSymbolsFromScope(s, untilScope) {
- const allUsedNames = new Set();
- let scope = s;
- while(scope) {
- if(untilScope === scope) break;
- scope.variables.forEach(variable => allUsedNames.add(variable.name));
- scope = scope.upper;
- }
- return allUsedNames;
-}
-
-function getAllReferences(variable) {
- let set = variable.references;
- // Look for inner scope variables too (like in class Foo { t() { Foo } })
- const identifiers = new Set(variable.identifiers);
- for(const scope of variable.scope.childScopes) {
- for(const innerVar of scope.variables) {
- if(innerVar.identifiers.some(id => identifiers.has(id))) {
- set = set.concat(innerVar.references);
- break;
- }
- }
- }
- return set;
-}
-
-function reduceSet(a, b) {
- for(const item of b)
- a.add(item);
- return a;
-}
-
-function getPathInAst(ast, node) {
- if(ast === node) {
- return [];
- }
- const nr = node.range;
- var i;
- if(Array.isArray(ast)) {
- for(i = 0; i < ast.length; i++) {
- const enterResult = enterNode(ast[i]);
- if(typeof enterResult !== "undefined")
- return enterResult;
- }
- } else if(ast && typeof ast === "object") {
- const keys = Object.keys(ast);
- for(i = 0; i < keys.length; i++) {
- const value = ast[keys[i]];
- if(Array.isArray(value)) {
- const pathResult = getPathInAst(value, node);
- if(typeof pathResult !== "undefined")
- return pathResult;
- } else if(value && typeof value === "object") {
- const enterResult = enterNode(value);
- if(typeof enterResult !== "undefined")
- return enterResult;
- }
- }
- }
-
- function enterNode(n) {
- const r = n.range;
- if(r) {
- if(r[0] <= nr[0] && r[1] >= nr[1]) {
- const path = getPathInAst(n, node);
- if(path) {
- path.push(n);
- return path;
- }
- }
- }
- return undefined;
- }
-}
-
-class ConcatenatedModule extends Module {
- constructor(rootModule, modules) {
- super();
- super.setChunks(rootModule._chunks);
- this.rootModule = rootModule;
- this.usedExports = rootModule.usedExports;
- this.providedExports = rootModule.providedExports;
- this.optimizationBailout = rootModule.optimizationBailout;
- this.used = rootModule.used;
- this.index = rootModule.index;
- this.index2 = rootModule.index2;
- this.depth = rootModule.depth;
- this.built = modules.some(m => m.built);
- this.cacheable = modules.every(m => m.cacheable);
- const modulesSet = new Set(modules);
- this.reasons = rootModule.reasons.filter(reason => !(reason.dependency instanceof HarmonyImportDependency) || !modulesSet.has(reason.module));
- this.meta = rootModule.meta;
- this.moduleArgument = rootModule.moduleArgument;
- this.exportsArgument = rootModule.exportsArgument;
- this.strict = true;
- this._numberOfConcatenatedModules = modules.length;
-
- this.dependencies = [];
- this.dependenciesWarnings = [];
- this.dependenciesErrors = [];
- this.fileDependencies = [];
- this.contextDependencies = [];
- this.warnings = [];
- this.errors = [];
- this.assets = {};
- this._orderedConcatenationList = this._createOrderedConcatenationList(rootModule, modulesSet);
- for(const info of this._orderedConcatenationList) {
- if(info.type === "concatenated") {
- const m = info.module;
-
- // populate dependencies
- m.dependencies.filter(dep => !(dep instanceof HarmonyImportDependency) || !modulesSet.has(dep.module))
- .forEach(d => this.dependencies.push(d));
- // populate dep warning
- m.dependenciesWarnings.forEach(depWarning => this.dependenciesWarnings.push(depWarning));
- // populate dep errors
- m.dependenciesErrors.forEach(depError => this.dependenciesErrors.push(depError));
- // populate file dependencies
- if(m.fileDependencies) m.fileDependencies.forEach(file => this.fileDependencies.push(file));
- // populate context dependencies
- if(m.contextDependencies) m.contextDependencies.forEach(context => this.contextDependencies.push(context));
- // populate warnings
- m.warnings.forEach(warning => this.warnings.push(warning));
- // populate errors
- m.errors.forEach(error => this.errors.push(error));
-
- Object.assign(this.assets, m.assets);
- }
- }
- this._identifier = this._createIdentifier();
- }
-
- get modules() {
- return this._orderedConcatenationList
- .filter(info => info.type === "concatenated")
- .map(info => info.module);
- }
-
- identifier() {
- return this._identifier;
- }
-
- readableIdentifier(requestShortener) {
- return this.rootModule.readableIdentifier(requestShortener) + ` + ${this._numberOfConcatenatedModules - 1} modules`;
- }
-
- libIdent(options) {
- return this.rootModule.libIdent(options);
- }
-
- nameForCondition() {
- return this.rootModule.nameForCondition();
- }
-
- build(options, compilation, resolver, fs, callback) {
- throw new Error("Cannot build this module. It should be already built.");
- }
-
- size() {
- // Guess size from embedded modules
- return this._orderedConcatenationList.reduce((sum, info) => {
- switch(info.type) {
- case "concatenated":
- return sum + info.module.size();
- case "external":
- return sum + 5;
- }
- return sum;
- }, 0);
- }
-
- _createOrderedConcatenationList(rootModule, modulesSet) {
- const list = [];
- const set = new Set();
-
- function getConcatenatedImports(module) {
- // TODO need changes when merging with the pure-module branch
- const allDeps = module.dependencies
- .filter(dep => dep instanceof HarmonyImportDependency && dep.module);
-
- return allDeps.map(dep => () => dep.module);
- }
-
- function enterModule(getModule) {
- const module = getModule();
- if(set.has(module)) return;
- set.add(module);
- if(modulesSet.has(module)) {
- const imports = getConcatenatedImports(module);
- imports.forEach(enterModule);
- list.push({
- type: "concatenated",
- module
- });
- } else {
- list.push({
- type: "external",
- get module() {
- // We need to use a getter here, because the module in the dependency
- // could be replaced by some other process (i. e. also replaced with a
- // concatenated module)
- return getModule();
- }
- });
- }
- }
-
- enterModule(() => rootModule);
-
- return list;
- }
-
- _createIdentifier() {
- let orderedConcatenationListIdentifiers = "";
- for(let i = 0; i < this._orderedConcatenationList.length; i++) {
- if(this._orderedConcatenationList[i].type === "concatenated") {
- orderedConcatenationListIdentifiers += this._orderedConcatenationList[i].module.identifier();
- orderedConcatenationListIdentifiers += " ";
- }
- }
- const hash = crypto.createHash("md5");
- hash.update(orderedConcatenationListIdentifiers);
- return this.rootModule.identifier() + " " + hash.digest("hex");
- }
-
- source(dependencyTemplates, outputOptions, requestShortener) {
- // Metainfo for each module
- const modulesWithInfo = this._orderedConcatenationList.map((info, idx) => {
- switch(info.type) {
- case "concatenated":
- {
- const exportMap = new Map();
- const reexportMap = new Map();
- info.module.dependencies.forEach(dep => {
- if(dep instanceof HarmonyExportSpecifierDependency) {
- if(!exportMap.has(dep.name))
- exportMap.set(dep.name, dep.id);
- } else if(dep instanceof HarmonyExportExpressionDependency) {
- if(!exportMap.has("default"))
- exportMap.set("default", "__WEBPACK_MODULE_DEFAULT_EXPORT__");
- } else if(dep instanceof HarmonyExportImportedSpecifierDependency) {
- const exportName = dep.name;
- const importName = dep.id;
- const importedModule = dep.importDependency.module;
- if(exportName && importName) {
- if(!reexportMap.has(exportName)) {
- reexportMap.set(exportName, {
- module: importedModule,
- exportName: importName,
- dependency: dep
- });
- }
- } else if(exportName) {
- if(!reexportMap.has(exportName)) {
- reexportMap.set(exportName, {
- module: importedModule,
- exportName: true,
- dependency: dep
- });
- }
- } else if(importedModule) {
- importedModule.providedExports.forEach(name => {
- if(dep.activeExports.has(name) || name === "default")
- return;
- if(!reexportMap.has(name)) {
- reexportMap.set(name, {
- module: importedModule,
- exportName: name,
- dependency: dep
- });
- }
- });
- }
- }
- });
- return {
- type: "concatenated",
- module: info.module,
- index: idx,
- ast: undefined,
- source: undefined,
- globalScope: undefined,
- moduleScope: undefined,
- internalNames: new Map(),
- exportMap: exportMap,
- reexportMap: reexportMap,
- hasNamespaceObject: false,
- namespaceObjectSource: null
- };
- }
- case "external":
- return {
- type: "external",
- module: info.module,
- index: idx,
- name: undefined,
- interopName: undefined,
- interop: undefined
- };
- default:
- throw new Error(`Unsupported concatenation entry type ${info.type}`);
- }
- });
-
- // Create mapping from module to info
- const moduleToInfoMap = new Map();
- modulesWithInfo.forEach(m => moduleToInfoMap.set(m.module, m));
-
- // Configure template decorators for dependencies
- const innerDependencyTemplates = new Map(dependencyTemplates);
-
- innerDependencyTemplates.set(HarmonyImportSpecifierDependency, new HarmonyImportSpecifierDependencyConcatenatedTemplate(
- dependencyTemplates.get(HarmonyImportSpecifierDependency),
- moduleToInfoMap
- ));
- innerDependencyTemplates.set(HarmonyImportDependency, new HarmonyImportDependencyConcatenatedTemplate(
- dependencyTemplates.get(HarmonyImportDependency),
- moduleToInfoMap
- ));
- innerDependencyTemplates.set(HarmonyExportSpecifierDependency, new HarmonyExportSpecifierDependencyConcatenatedTemplate(
- dependencyTemplates.get(HarmonyExportSpecifierDependency),
- this.rootModule
- ));
- innerDependencyTemplates.set(HarmonyExportExpressionDependency, new HarmonyExportExpressionDependencyConcatenatedTemplate(
- dependencyTemplates.get(HarmonyExportExpressionDependency),
- this.rootModule,
- moduleToInfoMap
- ));
- innerDependencyTemplates.set(HarmonyExportImportedSpecifierDependency, new HarmonyExportImportedSpecifierDependencyConcatenatedTemplate(
- dependencyTemplates.get(HarmonyExportImportedSpecifierDependency),
- this.rootModule,
- moduleToInfoMap
- ));
- innerDependencyTemplates.set(HarmonyCompatibilityDependency, new HarmonyCompatibilityDependencyConcatenatedTemplate(
- dependencyTemplates.get(HarmonyCompatibilityDependency),
- this.rootModule,
- moduleToInfoMap
- ));
- innerDependencyTemplates.set("hash", innerDependencyTemplates.get("hash") + this.rootModule.identifier());
-
- // Generate source code and analyse scopes
- // Prepare a ReplaceSource for the final source
- modulesWithInfo.forEach(info => {
- if(info.type === "concatenated") {
- const m = info.module;
- const source = m.source(innerDependencyTemplates, outputOptions, requestShortener);
- const code = source.source();
- let ast;
- try {
- ast = acorn.parse(code, {
- ranges: true,
- locations: true,
- ecmaVersion: Parser.ECMA_VERSION,
- sourceType: "module"
- });
- } catch(err) {
- if(err.loc && typeof err.loc === "object" && typeof err.loc.line === "number") {
- const lineNumber = err.loc.line;
- const lines = code.split("\n");
- err.message += "\n| " + lines.slice(Math.max(0, lineNumber - 3), lineNumber + 2).join("\n| ");
- }
- throw err;
- }
- const scopeManager = escope.analyze(ast, {
- ecmaVersion: 6,
- sourceType: "module",
- optimistic: true,
- ignoreEval: true,
- impliedStrict: true
- });
- const globalScope = scopeManager.acquire(ast);
- const moduleScope = globalScope.childScopes[0];
- const resultSource = new ReplaceSource(source);
- info.ast = ast;
- info.source = resultSource;
- info.globalScope = globalScope;
- info.moduleScope = moduleScope;
- }
- });
-
- // List of all used names to avoid conflicts
- const allUsedNames = new Set([
- "__WEBPACK_MODULE_DEFAULT_EXPORT__", // avoid using this internal name
-
- "abstract", "arguments", "async", "await", "boolean", "break", "byte", "case", "catch", "char", "class",
- "const", "continue", "debugger", "default", "delete", "do", "double", "else", "enum", "eval",
- "export", "extends", "false", "final", "finally", "float", "for", "function", "goto", "if",
- "implements", "import", "in", "instanceof", "int", "interface", "let", "long", "native", "new",
- "null", "package", "private", "protected", "public", "return", "short", "static", "super",
- "switch", "synchronized", "this", "throw", "throws", "transient", "true", "try", "typeof",
- "var", "void", "volatile", "while", "with", "yield",
-
- "module", "__dirname", "__filename", "exports",
-
- "Array", "Date", "eval", "function", "hasOwnProperty", "Infinity", "isFinite", "isNaN",
- "isPrototypeOf", "length", "Math", "NaN", "name", "Number", "Object", "prototype", "String",
- "toString", "undefined", "valueOf",
-
- "alert", "all", "anchor", "anchors", "area", "assign", "blur", "button", "checkbox",
- "clearInterval", "clearTimeout", "clientInformation", "close", "closed", "confirm", "constructor",
- "crypto", "decodeURI", "decodeURIComponent", "defaultStatus", "document", "element", "elements",
- "embed", "embeds", "encodeURI", "encodeURIComponent", "escape", "event", "fileUpload", "focus",
- "form", "forms", "frame", "innerHeight", "innerWidth", "layer", "layers", "link", "location",
- "mimeTypes", "navigate", "navigator", "frames", "frameRate", "hidden", "history", "image",
- "images", "offscreenBuffering", "open", "opener", "option", "outerHeight", "outerWidth",
- "packages", "pageXOffset", "pageYOffset", "parent", "parseFloat", "parseInt", "password", "pkcs11",
- "plugin", "prompt", "propertyIsEnum", "radio", "reset", "screenX", "screenY", "scroll", "secure",
- "select", "self", "setInterval", "setTimeout", "status", "submit", "taint", "text", "textarea",
- "top", "unescape", "untaint", "window",
-
- "onblur", "onclick", "onerror", "onfocus", "onkeydown", "onkeypress", "onkeyup", "onmouseover",
- "onload", "onmouseup", "onmousedown", "onsubmit"
- ]);
-
- // get all global names
- modulesWithInfo.forEach(info => {
- if(info.globalScope) {
- info.globalScope.through.forEach(reference => {
- const name = reference.identifier.name;
- if(/^__WEBPACK_MODULE_REFERENCE__\d+_([\da-f]+|ns)(_call)?__$/.test(name)) {
- for(const s of getSymbolsFromScope(reference.from, info.moduleScope)) {
- allUsedNames.add(s);
- }
- } else {
- allUsedNames.add(name);
- }
- });
- }
- });
-
- // generate names for symbols
- modulesWithInfo.forEach(info => {
- switch(info.type) {
- case "concatenated":
- {
- const namespaceObjectName = this.findNewName("namespaceObject", allUsedNames, null, info.module.readableIdentifier(requestShortener));
- allUsedNames.add(namespaceObjectName);
- info.internalNames.set(namespaceObjectName, namespaceObjectName);
- info.exportMap.set(true, namespaceObjectName);
- info.moduleScope.variables.forEach(variable => {
- const name = variable.name;
- if(allUsedNames.has(name)) {
- const references = getAllReferences(variable);
- const symbolsInReferences = references.map(ref => getSymbolsFromScope(ref.from, info.moduleScope)).reduce(reduceSet, new Set());
- const newName = this.findNewName(name, allUsedNames, symbolsInReferences, info.module.readableIdentifier(requestShortener));
- allUsedNames.add(newName);
- info.internalNames.set(name, newName);
- const source = info.source;
- const allIdentifiers = new Set(references.map(r => r.identifier).concat(variable.identifiers));
- for(const identifier of allIdentifiers) {
- const r = identifier.range;
- const path = getPathInAst(info.ast, identifier);
- if(path && path.length > 1 && path[1].type === "Property" && path[1].shorthand) {
- source.insert(r[1], `: ${newName}`);
- } else {
- source.replace(r[0], r[1] - 1, newName);
- }
- }
- } else {
- allUsedNames.add(name);
- info.internalNames.set(name, name);
- }
- });
- break;
- }
- case "external":
- {
- info.interop = info.module.meta && !info.module.meta.harmonyModule;
- const externalName = this.findNewName("", allUsedNames, null, info.module.readableIdentifier(requestShortener));
- allUsedNames.add(externalName);
- info.name = externalName;
- if(info.interop) {
- const externalNameInterop = this.findNewName("default", allUsedNames, null, info.module.readableIdentifier(requestShortener));
- allUsedNames.add(externalNameInterop);
- info.interopName = externalNameInterop;
- }
- break;
- }
- }
- });
-
- // Find and replace referenced to modules
- modulesWithInfo.forEach(info => {
- if(info.type === "concatenated") {
- info.globalScope.through.forEach(reference => {
- const name = reference.identifier.name;
- const match = /^__WEBPACK_MODULE_REFERENCE__(\d+)_([\da-f]+|ns)(_call)?__$/.exec(name);
- if(match) {
- const referencedModule = modulesWithInfo[+match[1]];
- let exportName;
- if(match[2] === "ns") {
- exportName = true;
- } else {
- const exportData = match[2];
- exportName = new Buffer(exportData, "hex").toString("utf-8"); // eslint-disable-line node/no-deprecated-api
- }
- const asCall = !!match[3];
- const finalName = getFinalName(referencedModule, exportName, moduleToInfoMap, requestShortener, asCall);
- const r = reference.identifier.range;
- const source = info.source;
- source.replace(r[0], r[1] - 1, finalName);
- }
- });
- }
- });
-
- const result = new ConcatSource();
-
- // add harmony compatibility flag (must be first because of possible circular dependencies)
- const usedExports = this.rootModule.usedExports;
- if(usedExports === true) {
- result.add(`Object.defineProperty(${this.exportsArgument || "exports"}, "__esModule", { value: true });\n`);
- }
-
- // define required namespace objects (must be before evaluation modules)
- modulesWithInfo.forEach(info => {
- if(info.namespaceObjectSource) {
- result.add(info.namespaceObjectSource);
- }
- });
-
- // evaluate modules in order
- modulesWithInfo.forEach(info => {
- switch(info.type) {
- case "concatenated":
- result.add(`\n// CONCATENATED MODULE: ${info.module.readableIdentifier(requestShortener)}\n`);
- result.add(info.source);
- break;
- case "external":
- result.add(`\n// EXTERNAL MODULE: ${info.module.readableIdentifier(requestShortener)}\n`);
- result.add(`var ${info.name} = __webpack_require__(${JSON.stringify(info.module.id)});\n`);
- if(info.interop) {
- result.add(`var ${info.interopName} = /*#__PURE__*/__webpack_require__.n(${info.name});\n`);
- }
- break;
- default:
- throw new Error(`Unsupported concatenation entry type ${info.type}`);
- }
- });
-
- return result;
- }
-
- findNewName(oldName, usedNamed1, usedNamed2, extraInfo) {
- let name = oldName;
-
- if(name === "__WEBPACK_MODULE_DEFAULT_EXPORT__")
- name = "";
-
- // Remove uncool stuff
- extraInfo = extraInfo.replace(/\.+\/|(\/index)?\.([a-zA-Z0-9]{1,4})($|\s|\?)|\s*\+\s*\d+\s*modules/g, "");
-
- const splittedInfo = extraInfo.split("/");
- while(splittedInfo.length) {
- name = splittedInfo.pop() + (name ? "_" + name : "");
- const nameIdent = Template.toIdentifier(name);
- if(!usedNamed1.has(nameIdent) && (!usedNamed2 || !usedNamed2.has(nameIdent))) return nameIdent;
- }
-
- let i = 0;
- let nameWithNumber = Template.toIdentifier(`${name}_${i}`);
- while(usedNamed1.has(nameWithNumber) || (usedNamed2 && usedNamed2.has(nameWithNumber))) {
- i++;
- nameWithNumber = Template.toIdentifier(`${name}_${i}`);
- }
- return nameWithNumber;
- }
-
- updateHash(hash) {
- for(const info of this._orderedConcatenationList) {
- switch(info.type) {
- case "concatenated":
- info.module.updateHash(hash);
- break;
- case "external":
- hash.update(`${info.module.id}`);
- break;
- }
- }
- super.updateHash(hash);
- }
-
-}
-
-class HarmonyImportSpecifierDependencyConcatenatedTemplate {
- constructor(originalTemplate, modulesMap) {
- this.originalTemplate = originalTemplate;
- this.modulesMap = modulesMap;
- }
-
- apply(dep, source, outputOptions, requestShortener, dependencyTemplates) {
- const module = dep.importDependency.module;
- const info = this.modulesMap.get(module);
- if(!info) {
- this.originalTemplate.apply(dep, source, outputOptions, requestShortener, dependencyTemplates);
- return;
- }
- let content;
- if(dep.id === null) {
- content = `__WEBPACK_MODULE_REFERENCE__${info.index}_ns__`;
- } else if(dep.namespaceObjectAsContext) {
- content = `__WEBPACK_MODULE_REFERENCE__${info.index}_ns__[${JSON.stringify(dep.id)}]`;
- } else {
- const exportData = new Buffer(dep.id, "utf-8").toString("hex"); // eslint-disable-line node/no-deprecated-api
- content = `__WEBPACK_MODULE_REFERENCE__${info.index}_${exportData}${dep.call ? "_call" : ""}__`;
- }
- if(dep.shorthand) {
- content = dep.name + ": " + content;
- }
- source.replace(dep.range[0], dep.range[1] - 1, content);
- }
-}
-
-class HarmonyImportDependencyConcatenatedTemplate {
- constructor(originalTemplate, modulesMap) {
- this.originalTemplate = originalTemplate;
- this.modulesMap = modulesMap;
- }
-
- apply(dep, source, outputOptions, requestShortener, dependencyTemplates) {
- const module = dep.module;
- const info = this.modulesMap.get(module);
- if(!info) {
- this.originalTemplate.apply(dep, source, outputOptions, requestShortener, dependencyTemplates);
- return;
- }
- source.replace(dep.range[0], dep.range[1] - 1, "");
- }
-}
-
-class HarmonyExportSpecifierDependencyConcatenatedTemplate {
- constructor(originalTemplate, rootModule) {
- this.originalTemplate = originalTemplate;
- this.rootModule = rootModule;
- }
-
- apply(dep, source, outputOptions, requestShortener, dependencyTemplates) {
- if(dep.originModule === this.rootModule) {
- this.originalTemplate.apply(dep, source, outputOptions, requestShortener, dependencyTemplates);
- }
- }
-}
-
-class HarmonyExportExpressionDependencyConcatenatedTemplate {
- constructor(originalTemplate, rootModule) {
- this.originalTemplate = originalTemplate;
- this.rootModule = rootModule;
- }
-
- apply(dep, source, outputOptions, requestShortener, dependencyTemplates) {
- let content = "/* harmony default export */ var __WEBPACK_MODULE_DEFAULT_EXPORT__ = ";
- if(dep.originModule === this.rootModule) {
- const used = dep.originModule.isUsed("default");
- const exportsName = dep.originModule.exportsArgument || "exports";
- if(used) content += `${exportsName}[${JSON.stringify(used)}] = `;
- }
-
- if(dep.range) {
- source.replace(dep.rangeStatement[0], dep.range[0] - 1, content + "(");
- source.replace(dep.range[1], dep.rangeStatement[1] - 1, ");");
- return;
- }
-
- source.replace(dep.rangeStatement[0], dep.rangeStatement[1] - 1, content);
- }
-}
-
-class HarmonyExportImportedSpecifierDependencyConcatenatedTemplate {
- constructor(originalTemplate, rootModule, modulesMap) {
- this.originalTemplate = originalTemplate;
- this.rootModule = rootModule;
- this.modulesMap = modulesMap;
- }
-
- getExports(dep) {
- const importModule = dep.importDependency.module;
- if(dep.id) {
- // export { named } from "module"
- return [{
- name: dep.name,
- id: dep.id,
- module: importModule
- }];
- }
- if(dep.name) {
- // export * as abc from "module"
- return [{
- name: dep.name,
- id: true,
- module: importModule
- }];
- }
- // export * from "module"
- return importModule.providedExports.filter(exp => exp !== "default" && !dep.activeExports.has(exp)).map(exp => {
- return {
- name: exp,
- id: exp,
- module: importModule
- };
- });
- }
-
- apply(dep, source, outputOptions, requestShortener, dependencyTemplates) {
- if(dep.originModule === this.rootModule) {
- if(this.modulesMap.get(dep.importDependency.module)) {
- const exportDefs = this.getExports(dep);
- exportDefs.forEach(def => {
- const info = this.modulesMap.get(def.module);
- const used = dep.originModule.isUsed(def.name);
- if(!used) {
- source.insert(-1, `/* unused concated harmony import ${dep.name} */\n`);
- }
- let finalName;
- if(def.id === true) {
- finalName = `__WEBPACK_MODULE_REFERENCE__${info.index}_ns__`;
- } else {
- const exportData = new Buffer(def.id, "utf-8").toString("hex"); // eslint-disable-line node/no-deprecated-api
- finalName = `__WEBPACK_MODULE_REFERENCE__${info.index}_${exportData}__`;
- }
- const exportsName = this.rootModule.exportsArgument || "exports";
- const content = `/* concated harmony reexport */__webpack_require__.d(${exportsName}, ${JSON.stringify(used)}, function() { return ${finalName}; });\n`;
- source.insert(-1, content);
- });
- } else {
- this.originalTemplate.apply(dep, source, outputOptions, requestShortener, dependencyTemplates);
- }
- }
- }
-}
-
-class HarmonyCompatibilityDependencyConcatenatedTemplate {
- constructor(originalTemplate, rootModule, modulesMap) {
- this.originalTemplate = originalTemplate;
- this.rootModule = rootModule;
- this.modulesMap = modulesMap;
- }
-
- apply(dep, source, outputOptions, requestShortener, dependencyTemplates) {
- // do nothing
- }
-}
-
-module.exports = ConcatenatedModule;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Module = require("../Module"); +const Template = require("../Template"); +const Parser = require("../Parser"); +const eslintScope = require("eslint-scope"); +const { ConcatSource, ReplaceSource } = require("webpack-sources"); +const DependencyReference = require("../dependencies/DependencyReference"); +const HarmonyImportDependency = require("../dependencies/HarmonyImportDependency"); +const HarmonyImportSideEffectDependency = require("../dependencies/HarmonyImportSideEffectDependency"); +const HarmonyImportSpecifierDependency = require("../dependencies/HarmonyImportSpecifierDependency"); +const HarmonyExportSpecifierDependency = require("../dependencies/HarmonyExportSpecifierDependency"); +const HarmonyExportExpressionDependency = require("../dependencies/HarmonyExportExpressionDependency"); +const HarmonyExportImportedSpecifierDependency = require("../dependencies/HarmonyExportImportedSpecifierDependency"); +const HarmonyCompatibilityDependency = require("../dependencies/HarmonyCompatibilityDependency"); +const createHash = require("../util/createHash"); + +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../util/createHash").Hash} Hash */ + +/** + * @typedef {Object} ConcatenationEntry + * @property {"concatenated" | "external"} type + * @property {Module} module + */ + +const ensureNsObjSource = ( + info, + moduleToInfoMap, + requestShortener, + strictHarmonyModule +) => { + if (!info.hasNamespaceObject) { + info.hasNamespaceObject = true; + const name = info.exportMap.get(true); + const nsObj = [`var ${name} = {};`, `__webpack_require__.r(${name});`]; + for (const exportName of info.module.buildMeta.providedExports) { + const finalName = getFinalName( + info, + exportName, + moduleToInfoMap, + requestShortener, + false, + strictHarmonyModule + ); + nsObj.push( + `__webpack_require__.d(${name}, ${JSON.stringify( + exportName + )}, function() { return ${finalName}; });` + ); + } + info.namespaceObjectSource = nsObj.join("\n") + "\n"; + } +}; + +const getExternalImport = ( + importedModule, + info, + exportName, + asCall, + strictHarmonyModule +) => { + const used = importedModule.isUsed(exportName); + if (!used) return "/* unused reexport */undefined"; + const comment = + used !== exportName ? ` ${Template.toNormalComment(exportName)}` : ""; + switch (importedModule.buildMeta.exportsType) { + case "named": + if (exportName === "default") { + return info.name; + } else if (exportName === true) { + info.interopNamespaceObjectUsed = true; + return info.interopNamespaceObjectName; + } else { + break; + } + case "namespace": + if (exportName === true) { + return info.name; + } else { + break; + } + default: + if (strictHarmonyModule) { + if (exportName === "default") { + return info.name; + } else if (exportName === true) { + info.interopNamespaceObjectUsed = true; + return info.interopNamespaceObjectName; + } else { + return "/* non-default import from non-esm module */undefined"; + } + } else { + if (exportName === "default") { + info.interopDefaultAccessUsed = true; + return asCall + ? `${info.interopDefaultAccessName}()` + : `${info.interopDefaultAccessName}.a`; + } else if (exportName === true) { + return info.name; + } else { + break; + } + } + } + const reference = `${info.name}[${JSON.stringify(used)}${comment}]`; + if (asCall) return `Object(${reference})`; + return reference; +}; + +const getFinalName = ( + info, + exportName, + moduleToInfoMap, + requestShortener, + asCall, + strictHarmonyModule, + alreadyVisited = new Set() +) => { + switch (info.type) { + case "concatenated": { + const directExport = info.exportMap.get(exportName); + if (directExport) { + if (exportName === true) { + ensureNsObjSource( + info, + moduleToInfoMap, + requestShortener, + strictHarmonyModule + ); + } else if (!info.module.isUsed(exportName)) { + return "/* unused export */ undefined"; + } + if (info.globalExports.has(directExport)) { + return directExport; + } + const name = info.internalNames.get(directExport); + if (!name) { + throw new Error( + `The export "${directExport}" in "${info.module.readableIdentifier( + requestShortener + )}" has no internal name` + ); + } + return name; + } + const reexport = info.reexportMap.get(exportName); + if (reexport) { + if (alreadyVisited.has(reexport)) { + throw new Error( + `Circular reexports ${Array.from( + alreadyVisited, + e => + `"${e.module.readableIdentifier(requestShortener)}".${ + e.exportName + }` + ).join( + " --> " + )} -(circular)-> "${reexport.module.readableIdentifier( + requestShortener + )}".${reexport.exportName}` + ); + } + alreadyVisited.add(reexport); + const refInfo = moduleToInfoMap.get(reexport.module); + if (refInfo) { + // module is in the concatenation + return getFinalName( + refInfo, + reexport.exportName, + moduleToInfoMap, + requestShortener, + asCall, + strictHarmonyModule, + alreadyVisited + ); + } + } + const problem = + `Cannot get final name for export "${exportName}" in "${info.module.readableIdentifier( + requestShortener + )}"` + + ` (known exports: ${Array.from(info.exportMap.keys()) + .filter(name => name !== true) + .join(" ")}, ` + + `known reexports: ${Array.from(info.reexportMap.keys()).join(" ")})`; + return `${Template.toNormalComment(problem)} undefined`; + } + case "external": { + const importedModule = info.module; + return getExternalImport( + importedModule, + info, + exportName, + asCall, + strictHarmonyModule + ); + } + } +}; + +const addScopeSymbols1 = (s, nameSet, scopeSet) => { + let scope = s; + while (scope) { + if (scopeSet.has(scope)) break; + scopeSet.add(scope); + for (const variable of scope.variables) { + nameSet.add(variable.name); + } + scope = scope.upper; + } +}; + +const addScopeSymbols2 = (s, nameSet, scopeSet1, scopeSet2) => { + let scope = s; + while (scope) { + if (scopeSet1.has(scope)) break; + if (scopeSet2.has(scope)) break; + scopeSet1.add(scope); + for (const variable of scope.variables) { + nameSet.add(variable.name); + } + scope = scope.upper; + } +}; + +const getAllReferences = variable => { + let set = variable.references; + // Look for inner scope variables too (like in class Foo { t() { Foo } }) + const identifiers = new Set(variable.identifiers); + for (const scope of variable.scope.childScopes) { + for (const innerVar of scope.variables) { + if (innerVar.identifiers.some(id => identifiers.has(id))) { + set = set.concat(innerVar.references); + break; + } + } + } + return set; +}; + +const getPathInAst = (ast, node) => { + if (ast === node) { + return []; + } + + const nr = node.range; + + const enterNode = n => { + if (!n) return undefined; + const r = n.range; + if (r) { + if (r[0] <= nr[0] && r[1] >= nr[1]) { + const path = getPathInAst(n, node); + if (path) { + path.push(n); + return path; + } + } + } + return undefined; + }; + + var i; + if (Array.isArray(ast)) { + for (i = 0; i < ast.length; i++) { + const enterResult = enterNode(ast[i]); + if (enterResult !== undefined) return enterResult; + } + } else if (ast && typeof ast === "object") { + const keys = Object.keys(ast); + for (i = 0; i < keys.length; i++) { + const value = ast[keys[i]]; + if (Array.isArray(value)) { + const pathResult = getPathInAst(value, node); + if (pathResult !== undefined) return pathResult; + } else if (value && typeof value === "object") { + const enterResult = enterNode(value); + if (enterResult !== undefined) return enterResult; + } + } + } +}; + +class ConcatenatedModule extends Module { + constructor(rootModule, modules, concatenationList) { + super("javascript/esm", null); + super.setChunks(rootModule._chunks); + + // Info from Factory + this.rootModule = rootModule; + this.factoryMeta = rootModule.factoryMeta; + + // Info from Compilation + this.index = rootModule.index; + this.index2 = rootModule.index2; + this.depth = rootModule.depth; + + // Info from Optimization + this.used = rootModule.used; + this.usedExports = rootModule.usedExports; + + // Info from Build + this.buildInfo = { + strict: true, + cacheable: modules.every(m => m.buildInfo.cacheable), + moduleArgument: rootModule.buildInfo.moduleArgument, + exportsArgument: rootModule.buildInfo.exportsArgument, + fileDependencies: new Set(), + contextDependencies: new Set(), + assets: undefined + }; + this.built = modules.some(m => m.built); + this.buildMeta = rootModule.buildMeta; + + // Caching + this._numberOfConcatenatedModules = modules.length; + + // Graph + const modulesSet = new Set(modules); + this.reasons = rootModule.reasons.filter( + reason => + !(reason.dependency instanceof HarmonyImportDependency) || + !modulesSet.has(reason.module) + ); + + this.dependencies = []; + + this.warnings = []; + this.errors = []; + this._orderedConcatenationList = + concatenationList || + ConcatenatedModule.createConcatenationList(rootModule, modulesSet, null); + for (const info of this._orderedConcatenationList) { + if (info.type === "concatenated") { + const m = info.module; + + // populate dependencies + for (const d of m.dependencies.filter( + dep => + !(dep instanceof HarmonyImportDependency) || + !modulesSet.has(dep._module) + )) { + this.dependencies.push(d); + } + // populate file dependencies + if (m.buildInfo.fileDependencies) { + for (const file of m.buildInfo.fileDependencies) { + this.buildInfo.fileDependencies.add(file); + } + } + // populate context dependencies + if (m.buildInfo.contextDependencies) { + for (const context of m.buildInfo.contextDependencies) { + this.buildInfo.contextDependencies.add(context); + } + } + // populate warnings + for (const warning of m.warnings) { + this.warnings.push(warning); + } + // populate errors + for (const error of m.errors) { + this.errors.push(error); + } + + if (m.buildInfo.assets) { + if (this.buildInfo.assets === undefined) { + this.buildInfo.assets = Object.create(null); + } + Object.assign(this.buildInfo.assets, m.buildInfo.assets); + } + } + } + this._identifier = this._createIdentifier(); + } + + get modules() { + return this._orderedConcatenationList + .filter(info => info.type === "concatenated") + .map(info => info.module); + } + + identifier() { + return this._identifier; + } + + readableIdentifier(requestShortener) { + return ( + this.rootModule.readableIdentifier(requestShortener) + + ` + ${this._numberOfConcatenatedModules - 1} modules` + ); + } + + libIdent(options) { + return this.rootModule.libIdent(options); + } + + nameForCondition() { + return this.rootModule.nameForCondition(); + } + + build(options, compilation, resolver, fs, callback) { + throw new Error("Cannot build this module. It should be already built."); + } + + size() { + // Guess size from embedded modules + return this._orderedConcatenationList.reduce((sum, info) => { + switch (info.type) { + case "concatenated": + return sum + info.module.size(); + case "external": + return sum + 5; + } + return sum; + }, 0); + } + + /** + * @param {Module} rootModule the root of the concatenation + * @param {Set<Module>} modulesSet a set of modules which should be concatenated + * @param {Compilation} compilation the compilation context + * @returns {ConcatenationEntry[]} concatenation list + */ + static createConcatenationList(rootModule, modulesSet, compilation) { + const list = []; + const set = new Set(); + + /** + * @param {Module} module a module + * @returns {(function(): Module)[]} imported modules in order + */ + const getConcatenatedImports = module => { + /** @type {WeakMap<DependencyReference, Dependency>} */ + const map = new WeakMap(); + const references = module.dependencies + .filter(dep => dep instanceof HarmonyImportDependency) + .map(dep => { + const ref = compilation.getDependencyReference(module, dep); + if (ref) map.set(ref, dep); + return ref; + }) + .filter(ref => ref); + DependencyReference.sort(references); + // TODO webpack 5: remove this hack, see also DependencyReference + return references.map(ref => { + const dep = map.get(ref); + return () => compilation.getDependencyReference(module, dep).module; + }); + }; + + const enterModule = getModule => { + const module = getModule(); + if (!module) return; + if (set.has(module)) return; + set.add(module); + if (modulesSet.has(module)) { + const imports = getConcatenatedImports(module); + imports.forEach(enterModule); + list.push({ + type: "concatenated", + module + }); + } else { + list.push({ + type: "external", + get module() { + // We need to use a getter here, because the module in the dependency + // could be replaced by some other process (i. e. also replaced with a + // concatenated module) + return getModule(); + } + }); + } + }; + + enterModule(() => rootModule); + + return list; + } + + _createIdentifier() { + let orderedConcatenationListIdentifiers = ""; + for (let i = 0; i < this._orderedConcatenationList.length; i++) { + if (this._orderedConcatenationList[i].type === "concatenated") { + orderedConcatenationListIdentifiers += this._orderedConcatenationList[ + i + ].module.identifier(); + orderedConcatenationListIdentifiers += " "; + } + } + const hash = createHash("md4"); + hash.update(orderedConcatenationListIdentifiers); + return this.rootModule.identifier() + " " + hash.digest("hex"); + } + + source(dependencyTemplates, runtimeTemplate) { + const requestShortener = runtimeTemplate.requestShortener; + // Metainfo for each module + const modulesWithInfo = this._orderedConcatenationList.map((info, idx) => { + switch (info.type) { + case "concatenated": { + const exportMap = new Map(); + const reexportMap = new Map(); + for (const dep of info.module.dependencies) { + if (dep instanceof HarmonyExportSpecifierDependency) { + if (!exportMap.has(dep.name)) { + exportMap.set(dep.name, dep.id); + } + } else if (dep instanceof HarmonyExportExpressionDependency) { + if (!exportMap.has("default")) { + exportMap.set("default", "__WEBPACK_MODULE_DEFAULT_EXPORT__"); + } + } else if ( + dep instanceof HarmonyExportImportedSpecifierDependency + ) { + const exportName = dep.name; + const importName = dep.id; + const importedModule = dep._module; + if (exportName && importName) { + if (!reexportMap.has(exportName)) { + reexportMap.set(exportName, { + module: importedModule, + exportName: importName, + dependency: dep + }); + } + } else if (exportName) { + if (!reexportMap.has(exportName)) { + reexportMap.set(exportName, { + module: importedModule, + exportName: true, + dependency: dep + }); + } + } else if (importedModule) { + for (const name of importedModule.buildMeta.providedExports) { + if (dep.activeExports.has(name) || name === "default") { + continue; + } + if (!reexportMap.has(name)) { + reexportMap.set(name, { + module: importedModule, + exportName: name, + dependency: dep + }); + } + } + } + } + } + return { + type: "concatenated", + module: info.module, + index: idx, + ast: undefined, + internalSource: undefined, + source: undefined, + globalScope: undefined, + moduleScope: undefined, + internalNames: new Map(), + globalExports: new Set(), + exportMap: exportMap, + reexportMap: reexportMap, + hasNamespaceObject: false, + namespaceObjectSource: null + }; + } + case "external": + return { + type: "external", + module: info.module, + index: idx, + name: undefined, + interopNamespaceObjectUsed: false, + interopNamespaceObjectName: undefined, + interopDefaultAccessUsed: false, + interopDefaultAccessName: undefined + }; + default: + throw new Error(`Unsupported concatenation entry type ${info.type}`); + } + }); + + // Create mapping from module to info + const moduleToInfoMap = new Map(); + for (const m of modulesWithInfo) { + moduleToInfoMap.set(m.module, m); + } + + // Configure template decorators for dependencies + const innerDependencyTemplates = new Map(dependencyTemplates); + + innerDependencyTemplates.set( + HarmonyImportSpecifierDependency, + new HarmonyImportSpecifierDependencyConcatenatedTemplate( + dependencyTemplates.get(HarmonyImportSpecifierDependency), + moduleToInfoMap + ) + ); + innerDependencyTemplates.set( + HarmonyImportSideEffectDependency, + new HarmonyImportSideEffectDependencyConcatenatedTemplate( + dependencyTemplates.get(HarmonyImportSideEffectDependency), + moduleToInfoMap + ) + ); + innerDependencyTemplates.set( + HarmonyExportSpecifierDependency, + new HarmonyExportSpecifierDependencyConcatenatedTemplate( + dependencyTemplates.get(HarmonyExportSpecifierDependency), + this.rootModule + ) + ); + innerDependencyTemplates.set( + HarmonyExportExpressionDependency, + new HarmonyExportExpressionDependencyConcatenatedTemplate( + dependencyTemplates.get(HarmonyExportExpressionDependency), + this.rootModule + ) + ); + innerDependencyTemplates.set( + HarmonyExportImportedSpecifierDependency, + new HarmonyExportImportedSpecifierDependencyConcatenatedTemplate( + dependencyTemplates.get(HarmonyExportImportedSpecifierDependency), + this.rootModule, + moduleToInfoMap + ) + ); + innerDependencyTemplates.set( + HarmonyCompatibilityDependency, + new HarmonyCompatibilityDependencyConcatenatedTemplate( + dependencyTemplates.get(HarmonyCompatibilityDependency), + this.rootModule, + moduleToInfoMap + ) + ); + + // Must use full identifier in our cache here to ensure that the source + // is updated should our dependencies list change. + // TODO webpack 5 refactor + innerDependencyTemplates.set( + "hash", + innerDependencyTemplates.get("hash") + this.identifier() + ); + + // Generate source code and analyse scopes + // Prepare a ReplaceSource for the final source + for (const info of modulesWithInfo) { + if (info.type === "concatenated") { + const m = info.module; + const source = m.source(innerDependencyTemplates, runtimeTemplate); + const code = source.source(); + let ast; + try { + ast = Parser.parse(code, { + sourceType: "module" + }); + } catch (err) { + if ( + err.loc && + typeof err.loc === "object" && + typeof err.loc.line === "number" + ) { + const lineNumber = err.loc.line; + const lines = code.split("\n"); + err.message += + "\n| " + + lines + .slice(Math.max(0, lineNumber - 3), lineNumber + 2) + .join("\n| "); + } + throw err; + } + const scopeManager = eslintScope.analyze(ast, { + ecmaVersion: 6, + sourceType: "module", + optimistic: true, + ignoreEval: true, + impliedStrict: true + }); + const globalScope = scopeManager.acquire(ast); + const moduleScope = globalScope.childScopes[0]; + const resultSource = new ReplaceSource(source); + info.ast = ast; + info.internalSource = source; + info.source = resultSource; + info.globalScope = globalScope; + info.moduleScope = moduleScope; + } + } + + // List of all used names to avoid conflicts + const allUsedNames = new Set([ + "__WEBPACK_MODULE_DEFAULT_EXPORT__", // avoid using this internal name + + "abstract", + "arguments", + "async", + "await", + "boolean", + "break", + "byte", + "case", + "catch", + "char", + "class", + "const", + "continue", + "debugger", + "default", + "delete", + "do", + "double", + "else", + "enum", + "eval", + "export", + "extends", + "false", + "final", + "finally", + "float", + "for", + "function", + "goto", + "if", + "implements", + "import", + "in", + "instanceof", + "int", + "interface", + "let", + "long", + "native", + "new", + "null", + "package", + "private", + "protected", + "public", + "return", + "short", + "static", + "super", + "switch", + "synchronized", + "this", + "throw", + "throws", + "transient", + "true", + "try", + "typeof", + "var", + "void", + "volatile", + "while", + "with", + "yield", + + "module", + "__dirname", + "__filename", + "exports", + + "Array", + "Date", + "eval", + "function", + "hasOwnProperty", + "Infinity", + "isFinite", + "isNaN", + "isPrototypeOf", + "length", + "Math", + "NaN", + "name", + "Number", + "Object", + "prototype", + "String", + "toString", + "undefined", + "valueOf", + + "alert", + "all", + "anchor", + "anchors", + "area", + "assign", + "blur", + "button", + "checkbox", + "clearInterval", + "clearTimeout", + "clientInformation", + "close", + "closed", + "confirm", + "constructor", + "crypto", + "decodeURI", + "decodeURIComponent", + "defaultStatus", + "document", + "element", + "elements", + "embed", + "embeds", + "encodeURI", + "encodeURIComponent", + "escape", + "event", + "fileUpload", + "focus", + "form", + "forms", + "frame", + "innerHeight", + "innerWidth", + "layer", + "layers", + "link", + "location", + "mimeTypes", + "navigate", + "navigator", + "frames", + "frameRate", + "hidden", + "history", + "image", + "images", + "offscreenBuffering", + "open", + "opener", + "option", + "outerHeight", + "outerWidth", + "packages", + "pageXOffset", + "pageYOffset", + "parent", + "parseFloat", + "parseInt", + "password", + "pkcs11", + "plugin", + "prompt", + "propertyIsEnum", + "radio", + "reset", + "screenX", + "screenY", + "scroll", + "secure", + "select", + "self", + "setInterval", + "setTimeout", + "status", + "submit", + "taint", + "text", + "textarea", + "top", + "unescape", + "untaint", + "window", + + "onblur", + "onclick", + "onerror", + "onfocus", + "onkeydown", + "onkeypress", + "onkeyup", + "onmouseover", + "onload", + "onmouseup", + "onmousedown", + "onsubmit" + ]); + + // Set of already checked scopes + const alreadyCheckedScopes = new Set(); + + // get all global names + for (const info of modulesWithInfo) { + const superClassExpressions = []; + + // ignore symbols from moduleScope + if (info.moduleScope) { + alreadyCheckedScopes.add(info.moduleScope); + + // The super class expression in class scopes behaves weird + // We store ranges of all super class expressions to make + // renaming to work correctly + for (const childScope of info.moduleScope.childScopes) { + if (childScope.type !== "class") continue; + if (!childScope.block.superClass) continue; + superClassExpressions.push({ + range: childScope.block.superClass.range, + variables: childScope.variables + }); + } + } + + // add global symbols + if (info.globalScope) { + for (const reference of info.globalScope.through) { + const name = reference.identifier.name; + if ( + /^__WEBPACK_MODULE_REFERENCE__\d+_([\da-f]+|ns)(_call)?(_strict)?__$/.test( + name + ) + ) { + for (const expr of superClassExpressions) { + if ( + expr.range[0] <= reference.identifier.range[0] && + expr.range[1] >= reference.identifier.range[1] + ) { + for (const variable of expr.variables) { + allUsedNames.add(variable.name); + } + } + } + addScopeSymbols1( + reference.from, + allUsedNames, + alreadyCheckedScopes + ); + } else { + allUsedNames.add(name); + } + } + } + + // add exported globals + if (info.type === "concatenated") { + const variables = new Set(); + for (const variable of info.moduleScope.variables) { + variables.add(variable.name); + } + for (const [, variable] of info.exportMap) { + if (!variables.has(variable)) { + info.globalExports.add(variable); + } + } + } + } + + // generate names for symbols + for (const info of modulesWithInfo) { + switch (info.type) { + case "concatenated": { + const namespaceObjectName = this.findNewName( + "namespaceObject", + allUsedNames, + null, + info.module.readableIdentifier(requestShortener) + ); + allUsedNames.add(namespaceObjectName); + info.internalNames.set(namespaceObjectName, namespaceObjectName); + info.exportMap.set(true, namespaceObjectName); + for (const variable of info.moduleScope.variables) { + const name = variable.name; + if (allUsedNames.has(name)) { + const references = getAllReferences(variable); + const symbolsInReferences = new Set(); + const alreadyCheckedInnerScopes = new Set(); + for (const ref of references) { + addScopeSymbols2( + ref.from, + symbolsInReferences, + alreadyCheckedInnerScopes, + alreadyCheckedScopes + ); + } + const newName = this.findNewName( + name, + allUsedNames, + symbolsInReferences, + info.module.readableIdentifier(requestShortener) + ); + allUsedNames.add(newName); + info.internalNames.set(name, newName); + const source = info.source; + const allIdentifiers = new Set( + references.map(r => r.identifier).concat(variable.identifiers) + ); + for (const identifier of allIdentifiers) { + const r = identifier.range; + const path = getPathInAst(info.ast, identifier); + if ( + path && + path.length > 1 && + path[1].type === "Property" && + path[1].shorthand + ) { + source.insert(r[1], `: ${newName}`); + } else { + source.replace(r[0], r[1] - 1, newName); + } + } + } else { + allUsedNames.add(name); + info.internalNames.set(name, name); + } + } + break; + } + case "external": { + const externalName = this.findNewName( + "", + allUsedNames, + null, + info.module.readableIdentifier(requestShortener) + ); + allUsedNames.add(externalName); + info.name = externalName; + if ( + info.module.buildMeta.exportsType === "named" || + !info.module.buildMeta.exportsType + ) { + const externalNameInterop = this.findNewName( + "namespaceObject", + allUsedNames, + null, + info.module.readableIdentifier(requestShortener) + ); + allUsedNames.add(externalNameInterop); + info.interopNamespaceObjectName = externalNameInterop; + } + if (!info.module.buildMeta.exportsType) { + const externalNameInterop = this.findNewName( + "default", + allUsedNames, + null, + info.module.readableIdentifier(requestShortener) + ); + allUsedNames.add(externalNameInterop); + info.interopDefaultAccessName = externalNameInterop; + } + break; + } + } + } + + // Find and replace referenced to modules + for (const info of modulesWithInfo) { + if (info.type === "concatenated") { + for (const reference of info.globalScope.through) { + const name = reference.identifier.name; + const match = /^__WEBPACK_MODULE_REFERENCE__(\d+)_([\da-f]+|ns)(_call)?(_strict)?__$/.exec( + name + ); + if (match) { + const referencedModule = modulesWithInfo[+match[1]]; + let exportName; + if (match[2] === "ns") { + exportName = true; + } else { + const exportData = match[2]; + exportName = Buffer.from(exportData, "hex").toString("utf-8"); + } + const asCall = !!match[3]; + const strictHarmonyModule = !!match[4]; + const finalName = getFinalName( + referencedModule, + exportName, + moduleToInfoMap, + requestShortener, + asCall, + strictHarmonyModule + ); + const r = reference.identifier.range; + const source = info.source; + source.replace(r[0], r[1] - 1, finalName); + } + } + } + } + + const result = new ConcatSource(); + + // add harmony compatibility flag (must be first because of possible circular dependencies) + const usedExports = this.rootModule.usedExports; + if (usedExports === true) { + result.add( + runtimeTemplate.defineEsModuleFlagStatement({ + exportsArgument: this.exportsArgument + }) + ); + } + + // define required namespace objects (must be before evaluation modules) + for (const info of modulesWithInfo) { + if (info.namespaceObjectSource) { + result.add(info.namespaceObjectSource); + } + } + + // evaluate modules in order + for (const info of modulesWithInfo) { + switch (info.type) { + case "concatenated": + result.add( + `\n// CONCATENATED MODULE: ${info.module.readableIdentifier( + requestShortener + )}\n` + ); + result.add(info.source); + break; + case "external": + result.add( + `\n// EXTERNAL MODULE: ${info.module.readableIdentifier( + requestShortener + )}\n` + ); + result.add( + `var ${info.name} = __webpack_require__(${JSON.stringify( + info.module.id + )});\n` + ); + if (info.interopNamespaceObjectUsed) { + if (info.module.buildMeta.exportsType === "named") { + result.add( + `var ${ + info.interopNamespaceObjectName + } = /*#__PURE__*/__webpack_require__.t(${info.name}, 2);\n` + ); + } else if (!info.module.buildMeta.exportsType) { + result.add( + `var ${ + info.interopNamespaceObjectName + } = /*#__PURE__*/__webpack_require__.t(${info.name});\n` + ); + } + } + if (info.interopDefaultAccessUsed) { + result.add( + `var ${ + info.interopDefaultAccessName + } = /*#__PURE__*/__webpack_require__.n(${info.name});\n` + ); + } + break; + default: + throw new Error(`Unsupported concatenation entry type ${info.type}`); + } + } + + return result; + } + + findNewName(oldName, usedNamed1, usedNamed2, extraInfo) { + let name = oldName; + + if (name === "__WEBPACK_MODULE_DEFAULT_EXPORT__") name = ""; + + // Remove uncool stuff + extraInfo = extraInfo.replace( + /\.+\/|(\/index)?\.([a-zA-Z0-9]{1,4})($|\s|\?)|\s*\+\s*\d+\s*modules/g, + "" + ); + + const splittedInfo = extraInfo.split("/"); + while (splittedInfo.length) { + name = splittedInfo.pop() + (name ? "_" + name : ""); + const nameIdent = Template.toIdentifier(name); + if ( + !usedNamed1.has(nameIdent) && + (!usedNamed2 || !usedNamed2.has(nameIdent)) + ) + return nameIdent; + } + + let i = 0; + let nameWithNumber = Template.toIdentifier(`${name}_${i}`); + while ( + usedNamed1.has(nameWithNumber) || + (usedNamed2 && usedNamed2.has(nameWithNumber)) + ) { + i++; + nameWithNumber = Template.toIdentifier(`${name}_${i}`); + } + return nameWithNumber; + } + + /** + * @param {Hash} hash the hash used to track dependencies + * @returns {void} + */ + updateHash(hash) { + for (const info of this._orderedConcatenationList) { + switch (info.type) { + case "concatenated": + info.module.updateHash(hash); + break; + case "external": + hash.update(`${info.module.id}`); + break; + } + } + super.updateHash(hash); + } +} + +class HarmonyImportSpecifierDependencyConcatenatedTemplate { + constructor(originalTemplate, modulesMap) { + this.originalTemplate = originalTemplate; + this.modulesMap = modulesMap; + } + + getHarmonyInitOrder(dep) { + const module = dep._module; + const info = this.modulesMap.get(module); + if (!info) { + return this.originalTemplate.getHarmonyInitOrder(dep); + } + return NaN; + } + + harmonyInit(dep, source, runtimeTemplate, dependencyTemplates) { + const module = dep._module; + const info = this.modulesMap.get(module); + if (!info) { + this.originalTemplate.harmonyInit( + dep, + source, + runtimeTemplate, + dependencyTemplates + ); + return; + } + } + + apply(dep, source, runtime, dependencyTemplates) { + const module = dep._module; + const info = this.modulesMap.get(module); + if (!info) { + this.originalTemplate.apply(dep, source, runtime, dependencyTemplates); + return; + } + let content; + const callFlag = dep.call ? "_call" : ""; + const strictFlag = dep.originModule.buildMeta.strictHarmonyModule + ? "_strict" + : ""; + if (dep._id === null) { + content = `__WEBPACK_MODULE_REFERENCE__${info.index}_ns${strictFlag}__`; + } else if (dep.namespaceObjectAsContext) { + content = `__WEBPACK_MODULE_REFERENCE__${ + info.index + }_ns${strictFlag}__[${JSON.stringify(dep._id)}]`; + } else { + const exportData = Buffer.from(dep._id, "utf-8").toString("hex"); + content = `__WEBPACK_MODULE_REFERENCE__${ + info.index + }_${exportData}${callFlag}${strictFlag}__`; + } + if (dep.shorthand) { + content = dep.name + ": " + content; + } + source.replace(dep.range[0], dep.range[1] - 1, content); + } +} + +class HarmonyImportSideEffectDependencyConcatenatedTemplate { + constructor(originalTemplate, modulesMap) { + this.originalTemplate = originalTemplate; + this.modulesMap = modulesMap; + } + + getHarmonyInitOrder(dep) { + const module = dep._module; + const info = this.modulesMap.get(module); + if (!info) { + return this.originalTemplate.getHarmonyInitOrder(dep); + } + return NaN; + } + + harmonyInit(dep, source, runtime, dependencyTemplates) { + const module = dep._module; + const info = this.modulesMap.get(module); + if (!info) { + this.originalTemplate.harmonyInit( + dep, + source, + runtime, + dependencyTemplates + ); + return; + } + } + + apply(dep, source, runtime, dependencyTemplates) { + const module = dep._module; + const info = this.modulesMap.get(module); + if (!info) { + this.originalTemplate.apply(dep, source, runtime, dependencyTemplates); + return; + } + } +} + +class HarmonyExportSpecifierDependencyConcatenatedTemplate { + constructor(originalTemplate, rootModule) { + this.originalTemplate = originalTemplate; + this.rootModule = rootModule; + } + + getHarmonyInitOrder(dep) { + if (dep.originModule === this.rootModule) { + return this.originalTemplate.getHarmonyInitOrder(dep); + } + return NaN; + } + + harmonyInit(dep, source, runtime, dependencyTemplates) { + if (dep.originModule === this.rootModule) { + this.originalTemplate.harmonyInit( + dep, + source, + runtime, + dependencyTemplates + ); + return; + } + } + + apply(dep, source, runtime, dependencyTemplates) { + if (dep.originModule === this.rootModule) { + this.originalTemplate.apply(dep, source, runtime, dependencyTemplates); + } + } +} + +class HarmonyExportExpressionDependencyConcatenatedTemplate { + constructor(originalTemplate, rootModule) { + this.originalTemplate = originalTemplate; + this.rootModule = rootModule; + } + + apply(dep, source, runtime, dependencyTemplates) { + let content = + "/* harmony default export */ var __WEBPACK_MODULE_DEFAULT_EXPORT__ = "; + if (dep.originModule === this.rootModule) { + const used = dep.originModule.isUsed("default"); + const exportsName = dep.originModule.exportsArgument; + if (used) content += `${exportsName}[${JSON.stringify(used)}] = `; + } + + if (dep.range) { + source.replace(dep.rangeStatement[0], dep.range[0] - 1, content + "("); + source.replace(dep.range[1], dep.rangeStatement[1] - 1, ");"); + return; + } + + source.replace(dep.rangeStatement[0], dep.rangeStatement[1] - 1, content); + } +} + +class HarmonyExportImportedSpecifierDependencyConcatenatedTemplate { + constructor(originalTemplate, rootModule, modulesMap) { + this.originalTemplate = originalTemplate; + this.rootModule = rootModule; + this.modulesMap = modulesMap; + } + + getExports(dep) { + const importModule = dep._module; + if (dep.id) { + // export { named } from "module" + return [ + { + name: dep.name, + id: dep.id, + module: importModule + } + ]; + } + if (dep.name) { + // export * as abc from "module" + return [ + { + name: dep.name, + id: true, + module: importModule + } + ]; + } + // export * from "module" + return importModule.buildMeta.providedExports + .filter(exp => exp !== "default" && !dep.activeExports.has(exp)) + .map(exp => { + return { + name: exp, + id: exp, + module: importModule + }; + }); + } + + getHarmonyInitOrder(dep) { + const module = dep._module; + const info = this.modulesMap.get(module); + if (!info) { + return this.originalTemplate.getHarmonyInitOrder(dep); + } + return NaN; + } + + harmonyInit(dep, source, runtime, dependencyTemplates) { + const module = dep._module; + const info = this.modulesMap.get(module); + if (!info) { + this.originalTemplate.harmonyInit( + dep, + source, + runtime, + dependencyTemplates + ); + return; + } + } + + apply(dep, source, runtime, dependencyTemplates) { + if (dep.originModule === this.rootModule) { + if (this.modulesMap.get(dep._module)) { + const exportDefs = this.getExports(dep); + for (const def of exportDefs) { + const info = this.modulesMap.get(def.module); + const used = dep.originModule.isUsed(def.name); + if (!used) { + source.insert( + -1, + `/* unused concated harmony import ${def.name} */\n` + ); + continue; + } + let finalName; + const strictFlag = dep.originModule.buildMeta.strictHarmonyModule + ? "_strict" + : ""; + if (def.id === true) { + finalName = `__WEBPACK_MODULE_REFERENCE__${ + info.index + }_ns${strictFlag}__`; + } else { + const exportData = Buffer.from(def.id, "utf-8").toString("hex"); + finalName = `__WEBPACK_MODULE_REFERENCE__${ + info.index + }_${exportData}${strictFlag}__`; + } + const exportsName = this.rootModule.exportsArgument; + const content = + `/* concated harmony reexport ${def.name} */` + + `__webpack_require__.d(${exportsName}, ` + + `${JSON.stringify(used)}, ` + + `function() { return ${finalName}; });\n`; + source.insert(-1, content); + } + } else { + this.originalTemplate.apply(dep, source, runtime, dependencyTemplates); + } + } + } +} + +class HarmonyCompatibilityDependencyConcatenatedTemplate { + constructor(originalTemplate, rootModule, modulesMap) { + this.originalTemplate = originalTemplate; + this.rootModule = rootModule; + this.modulesMap = modulesMap; + } + + apply(dep, source, runtime, dependencyTemplates) { + // do nothing + } +} + +module.exports = ConcatenatedModule; diff --git a/node_modules/webpack/lib/optimize/DedupePlugin.js b/node_modules/webpack/lib/optimize/DedupePlugin.js deleted file mode 100644 index cffa43aaf..000000000 --- a/node_modules/webpack/lib/optimize/DedupePlugin.js +++ /dev/null @@ -1,15 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-class DedupePlugin {
- apply(compiler) {
- compiler.plugin("compilation", (compilation) => {
- compilation.warnings.push(new Error("DedupePlugin: This plugin was removed from webpack. Remove it from your configuration."));
- });
- }
-}
-
-module.exports = DedupePlugin;
diff --git a/node_modules/webpack/lib/optimize/EnsureChunkConditionsPlugin.js b/node_modules/webpack/lib/optimize/EnsureChunkConditionsPlugin.js index 2b291fdad..5d05ec834 100644 --- a/node_modules/webpack/lib/optimize/EnsureChunkConditionsPlugin.js +++ b/node_modules/webpack/lib/optimize/EnsureChunkConditionsPlugin.js @@ -1,40 +1,70 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-class EnsureChunkConditionsPlugin {
-
- apply(compiler) {
- compiler.plugin("compilation", (compilation) => {
- const triesMap = new Map();
- compilation.plugin(["optimize-chunks-basic", "optimize-extracted-chunks-basic"], (chunks) => {
- let changed = false;
- chunks.forEach((chunk) => {
- chunk.forEachModule((module) => {
- if(!module.chunkCondition) return;
- if(!module.chunkCondition(chunk)) {
- let usedChunks = triesMap.get(module);
- if(!usedChunks) triesMap.set(module, usedChunks = new Set());
- usedChunks.add(chunk);
- const newChunks = [];
- chunk.parents.forEach((parent) => {
- if(!usedChunks.has(parent)) {
- parent.addModule(module);
- module.addChunk(parent);
- newChunks.push(parent);
- }
- });
- module.rewriteChunkInReasons(chunk, newChunks);
- chunk.removeModule(module);
- changed = true;
- }
- });
- });
- if(changed) return true;
- });
- });
- }
-}
-module.exports = EnsureChunkConditionsPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const GraphHelpers = require("../GraphHelpers"); + +class EnsureChunkConditionsPlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "EnsureChunkConditionsPlugin", + compilation => { + const handler = chunks => { + let changed = false; + for (const module of compilation.modules) { + if (!module.chunkCondition) continue; + const sourceChunks = new Set(); + const chunkGroups = new Set(); + for (const chunk of module.chunksIterable) { + if (!module.chunkCondition(chunk)) { + sourceChunks.add(chunk); + for (const group of chunk.groupsIterable) { + chunkGroups.add(group); + } + } + } + if (sourceChunks.size === 0) continue; + const targetChunks = new Set(); + chunkGroupLoop: for (const chunkGroup of chunkGroups) { + // Can module be placed in a chunk of this group? + for (const chunk of chunkGroup.chunks) { + if (module.chunkCondition(chunk)) { + targetChunks.add(chunk); + continue chunkGroupLoop; + } + } + // We reached the entrypoint: fail + if (chunkGroup.isInitial()) { + throw new Error( + "Cannot fullfil chunk condition of " + module.identifier() + ); + } + // Try placing in all parents + for (const group of chunkGroup.parentsIterable) { + chunkGroups.add(group); + } + } + for (const sourceChunk of sourceChunks) { + GraphHelpers.disconnectChunkAndModule(sourceChunk, module); + } + for (const targetChunk of targetChunks) { + GraphHelpers.connectChunkAndModule(targetChunk, module); + } + } + if (changed) return true; + }; + compilation.hooks.optimizeChunksBasic.tap( + "EnsureChunkConditionsPlugin", + handler + ); + compilation.hooks.optimizeExtractedChunksBasic.tap( + "EnsureChunkConditionsPlugin", + handler + ); + } + ); + } +} +module.exports = EnsureChunkConditionsPlugin; diff --git a/node_modules/webpack/lib/optimize/FlagIncludedChunksPlugin.js b/node_modules/webpack/lib/optimize/FlagIncludedChunksPlugin.js index 75277b5aa..1890f0581 100644 --- a/node_modules/webpack/lib/optimize/FlagIncludedChunksPlugin.js +++ b/node_modules/webpack/lib/optimize/FlagIncludedChunksPlugin.js @@ -1,35 +1,99 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-class FlagIncludedChunksPlugin {
-
- apply(compiler) {
- compiler.plugin("compilation", (compilation) => {
- compilation.plugin("optimize-chunk-ids", (chunks) => {
- chunks.forEach((chunkA) => {
- chunks.forEach((chunkB) => {
- // as we iterate the same iterables twice
- // skip if we find ourselves
- if(chunkA === chunkB) return;
-
- // instead of swapping A and B just bail
- // as we loop twice the current A will be B and B then A
- if(chunkA.getNumberOfModules() < chunkB.getNumberOfModules()) return;
-
- if(chunkB.getNumberOfModules() === 0) return;
-
- // is chunkB in chunkA?
- for(const m of chunkB.modulesIterable) {
- if(!chunkA.containsModule(m)) return;
- }
- chunkA.ids.push(chunkB.id);
- });
- });
- });
- });
- }
-}
-module.exports = FlagIncludedChunksPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +class FlagIncludedChunksPlugin { + apply(compiler) { + compiler.hooks.compilation.tap("FlagIncludedChunksPlugin", compilation => { + compilation.hooks.optimizeChunkIds.tap( + "FlagIncludedChunksPlugin", + chunks => { + // prepare two bit integers for each module + // 2^31 is the max number represented as SMI in v8 + // we want the bits distributed this way: + // the bit 2^31 is pretty rar and only one module should get it + // so it has a probability of 1 / modulesCount + // the first bit (2^0) is the easiest and every module could get it + // if it doesn't get a better bit + // from bit 2^n to 2^(n+1) there is a probability of p + // so 1 / modulesCount == p^31 + // <=> p = sqrt31(1 / modulesCount) + // so we use a modulo of 1 / sqrt31(1 / modulesCount) + const moduleBits = new WeakMap(); + const modulesCount = compilation.modules.length; + + // precalculate the modulo values for each bit + const modulo = 1 / Math.pow(1 / modulesCount, 1 / 31); + const modulos = Array.from( + { length: 31 }, + (x, i) => Math.pow(modulo, i) | 0 + ); + + // iterate all modules to generate bit values + let i = 0; + for (const module of compilation.modules) { + let bit = 30; + while (i % modulos[bit] !== 0) { + bit--; + } + moduleBits.set(module, 1 << bit); + i++; + } + + // interate all chunks to generate bitmaps + const chunkModulesHash = new WeakMap(); + for (const chunk of chunks) { + let hash = 0; + for (const module of chunk.modulesIterable) { + hash |= moduleBits.get(module); + } + chunkModulesHash.set(chunk, hash); + } + + for (const chunkA of chunks) { + const chunkAHash = chunkModulesHash.get(chunkA); + const chunkAModulesCount = chunkA.getNumberOfModules(); + if (chunkAModulesCount === 0) continue; + let bestModule = undefined; + for (const module of chunkA.modulesIterable) { + if ( + bestModule === undefined || + bestModule.getNumberOfChunks() > module.getNumberOfChunks() + ) + bestModule = module; + } + loopB: for (const chunkB of bestModule.chunksIterable) { + // as we iterate the same iterables twice + // skip if we find ourselves + if (chunkA === chunkB) continue; + + const chunkBModulesCount = chunkB.getNumberOfModules(); + + // ids for empty chunks are not included + if (chunkBModulesCount === 0) continue; + + // instead of swapping A and B just bail + // as we loop twice the current A will be B and B then A + if (chunkAModulesCount > chunkBModulesCount) continue; + + // is chunkA in chunkB? + + // we do a cheap check for the hash value + const chunkBHash = chunkModulesHash.get(chunkB); + if ((chunkBHash & chunkAHash) !== chunkAHash) continue; + + // compare all modules + for (const m of chunkA.modulesIterable) { + if (!chunkB.containsModule(m)) continue loopB; + } + chunkB.ids.push(chunkA.id); + } + } + } + ); + }); + } +} +module.exports = FlagIncludedChunksPlugin; diff --git a/node_modules/webpack/lib/optimize/LimitChunkCountPlugin.js b/node_modules/webpack/lib/optimize/LimitChunkCountPlugin.js index c156338ff..f38b942b1 100644 --- a/node_modules/webpack/lib/optimize/LimitChunkCountPlugin.js +++ b/node_modules/webpack/lib/optimize/LimitChunkCountPlugin.js @@ -1,59 +1,66 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-class LimitChunkCountPlugin {
- constructor(options) {
- if(options !== undefined && typeof options !== "object" || Array.isArray(options)) {
- throw new Error("Argument should be an options object.\nFor more info on options, see https://webpack.js.org/plugins/");
- }
- this.options = options || {};
- }
- apply(compiler) {
- const options = this.options;
- compiler.plugin("compilation", (compilation) => {
- compilation.plugin("optimize-chunks-advanced", (chunks) => {
- const maxChunks = options.maxChunks;
- if(!maxChunks) return;
- if(maxChunks < 1) return;
- if(chunks.length <= maxChunks) return;
-
- if(chunks.length > maxChunks) {
- const sortedExtendedPairCombinations = chunks.reduce((combinations, a, idx) => {
- // create combination pairs
- for(let i = 0; i < idx; i++) {
- const b = chunks[i];
- combinations.push([b, a]);
- }
- return combinations;
- }, []).map((pair) => {
- // extend combination pairs with size and integrated size
- const a = pair[0].size(options);
- const b = pair[1].size(options);
- const ab = pair[0].integratedSize(pair[1], options);
- return [a + b - ab, ab, pair[0], pair[1], a, b];
- }).filter((extendedPair) => {
- // filter pairs that do not have an integratedSize
- // meaning they can NOT be integrated!
- return extendedPair[1] !== false;
- }).sort((a, b) => { // sadly javascript does an inplace sort here
- // sort them by size
- const diff = b[0] - a[0];
- if(diff !== 0) return diff;
- return a[1] - b[1];
- });
-
- const pair = sortedExtendedPairCombinations[0];
-
- if(pair && pair[2].integrate(pair[3], "limit")) {
- chunks.splice(chunks.indexOf(pair[3]), 1);
- return true;
- }
- }
- });
- });
- }
-}
-module.exports = LimitChunkCountPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const validateOptions = require("schema-utils"); +const schema = require("../../schemas/plugins/optimize/LimitChunkCountPlugin.json"); + +class LimitChunkCountPlugin { + constructor(options) { + validateOptions(schema, options || {}, "Limit Chunk Count Plugin"); + this.options = options || {}; + } + apply(compiler) { + const options = this.options; + compiler.hooks.compilation.tap("LimitChunkCountPlugin", compilation => { + compilation.hooks.optimizeChunksAdvanced.tap( + "LimitChunkCountPlugin", + chunks => { + const maxChunks = options.maxChunks; + if (!maxChunks) return; + if (maxChunks < 1) return; + if (chunks.length <= maxChunks) return; + + const sortedExtendedPairCombinations = chunks + .reduce((combinations, a, idx) => { + // create combination pairs + for (let i = 0; i < idx; i++) { + const b = chunks[i]; + combinations.push([b, a]); + } + return combinations; + }, []) + .map(pair => { + // extend combination pairs with size and integrated size + const a = pair[0].size(options); + const b = pair[1].size(options); + const ab = pair[0].integratedSize(pair[1], options); + return [a + b - ab, ab, pair[0], pair[1], a, b]; + }) + .filter(extendedPair => { + // filter pairs that do not have an integratedSize + // meaning they can NOT be integrated! + return extendedPair[1] !== false; + }) + .sort((a, b) => { + // sadly javascript does an inplace sort here + // sort them by size + const diff = b[0] - a[0]; + if (diff !== 0) return diff; + return a[1] - b[1]; + }); + + const pair = sortedExtendedPairCombinations[0]; + + if (pair && pair[2].integrate(pair[3], "limit")) { + chunks.splice(chunks.indexOf(pair[3]), 1); + return true; + } + } + ); + }); + } +} +module.exports = LimitChunkCountPlugin; diff --git a/node_modules/webpack/lib/optimize/MergeDuplicateChunksPlugin.js b/node_modules/webpack/lib/optimize/MergeDuplicateChunksPlugin.js index 7b006fd17..1c3e23aa3 100644 --- a/node_modules/webpack/lib/optimize/MergeDuplicateChunksPlugin.js +++ b/node_modules/webpack/lib/optimize/MergeDuplicateChunksPlugin.js @@ -1,28 +1,78 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-class MergeDuplicateChunksPlugin {
-
- apply(compiler) {
- compiler.plugin("compilation", (compilation) => {
- compilation.plugin("optimize-chunks-basic", (chunks) => {
- const map = Object.create(null);
- chunks.slice().forEach((chunk) => {
- if(chunk.hasRuntime() || chunk.hasEntryModule()) return;
- const ident = chunk.getModulesIdent();
- const otherChunk = map[ident];
- if(otherChunk) {
- if(otherChunk.integrate(chunk, "duplicate"))
- chunks.splice(chunks.indexOf(chunk), 1);
- return;
- }
- map[ident] = chunk;
- });
- });
- });
- }
-}
-module.exports = MergeDuplicateChunksPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +class MergeDuplicateChunksPlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "MergeDuplicateChunksPlugin", + compilation => { + compilation.hooks.optimizeChunksBasic.tap( + "MergeDuplicateChunksPlugin", + chunks => { + // remember already tested chunks for performance + const notDuplicates = new Set(); + + // for each chunk + for (const chunk of chunks) { + // track a Set of all chunk that could be duplicates + let possibleDuplicates; + for (const module of chunk.modulesIterable) { + if (possibleDuplicates === undefined) { + // when possibleDuplicates is not yet set, + // create a new Set from chunks of the current module + // including only chunks with the same number of modules + for (const dup of module.chunksIterable) { + if ( + dup !== chunk && + chunk.getNumberOfModules() === dup.getNumberOfModules() && + !notDuplicates.has(dup) + ) { + // delay allocating the new Set until here, reduce memory pressure + if (possibleDuplicates === undefined) { + possibleDuplicates = new Set(); + } + possibleDuplicates.add(dup); + } + } + // when no chunk is possible we can break here + if (possibleDuplicates === undefined) break; + } else { + // validate existing possible duplicates + for (const dup of possibleDuplicates) { + // remove possible duplicate when module is not contained + if (!dup.containsModule(module)) { + possibleDuplicates.delete(dup); + } + } + // when all chunks has been removed we can break here + if (possibleDuplicates.size === 0) break; + } + } + + // when we found duplicates + if ( + possibleDuplicates !== undefined && + possibleDuplicates.size > 0 + ) { + for (const otherChunk of possibleDuplicates) { + if (otherChunk.hasRuntime() !== chunk.hasRuntime()) continue; + // merge them + if (chunk.integrate(otherChunk, "duplicate")) { + chunks.splice(chunks.indexOf(otherChunk), 1); + } + } + } + + // don't check already processed chunks twice + notDuplicates.add(chunk); + } + } + ); + } + ); + } +} +module.exports = MergeDuplicateChunksPlugin; diff --git a/node_modules/webpack/lib/optimize/MinChunkSizePlugin.js b/node_modules/webpack/lib/optimize/MinChunkSizePlugin.js index 87a4c21af..0f3893910 100644 --- a/node_modules/webpack/lib/optimize/MinChunkSizePlugin.js +++ b/node_modules/webpack/lib/optimize/MinChunkSizePlugin.js @@ -1,65 +1,77 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-class MinChunkSizePlugin {
- constructor(options) {
- if(typeof options !== "object" || Array.isArray(options)) {
- throw new Error("Argument should be an options object.\nFor more info on options, see https://webpack.js.org/plugins/");
- }
- this.options = options;
- }
-
- apply(compiler) {
- const options = this.options;
- const minChunkSize = options.minChunkSize;
- compiler.plugin("compilation", (compilation) => {
- compilation.plugin("optimize-chunks-advanced", (chunks) => {
- const equalOptions = {
- chunkOverhead: 1,
- entryChunkMultiplicator: 1
- };
-
- const sortedSizeFilteredExtendedPairCombinations = chunks.reduce((combinations, a, idx) => {
- // create combination pairs
- for(let i = 0; i < idx; i++) {
- const b = chunks[i];
- combinations.push([b, a]);
- }
- return combinations;
- }, []).filter((pair) => {
- // check if one of the chunks sizes is smaller than the minChunkSize
- const p0SmallerThanMinChunkSize = pair[0].size(equalOptions) < minChunkSize;
- const p1SmallerThanMinChunkSize = pair[1].size(equalOptions) < minChunkSize;
- return p0SmallerThanMinChunkSize || p1SmallerThanMinChunkSize;
- }).map((pair) => {
- // extend combination pairs with size and integrated size
- const a = pair[0].size(options);
- const b = pair[1].size(options);
- const ab = pair[0].integratedSize(pair[1], options);
- return [a + b - ab, ab, pair[0], pair[1]];
- }).filter((pair) => {
- // filter pairs that do not have an integratedSize
- // meaning they can NOT be integrated!
- return pair[1] !== false;
- }).sort((a, b) => { // sadly javascript does an inplace sort here
- // sort by size
- const diff = b[0] - a[0];
- if(diff !== 0) return diff;
- return a[1] - b[1];
- });
-
- if(sortedSizeFilteredExtendedPairCombinations.length === 0) return;
-
- const pair = sortedSizeFilteredExtendedPairCombinations[0];
-
- pair[2].integrate(pair[3], "min-size");
- chunks.splice(chunks.indexOf(pair[3]), 1);
- return true;
- });
- });
- }
-}
-module.exports = MinChunkSizePlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const validateOptions = require("schema-utils"); +const schema = require("../../schemas/plugins/optimize/MinChunkSizePlugin.json"); + +class MinChunkSizePlugin { + constructor(options) { + validateOptions(schema, options, "Min Chunk Size Plugin"); + this.options = options; + } + + apply(compiler) { + const options = this.options; + const minChunkSize = options.minChunkSize; + compiler.hooks.compilation.tap("MinChunkSizePlugin", compilation => { + compilation.hooks.optimizeChunksAdvanced.tap( + "MinChunkSizePlugin", + chunks => { + const equalOptions = { + chunkOverhead: 1, + entryChunkMultiplicator: 1 + }; + + const sortedSizeFilteredExtendedPairCombinations = chunks + .reduce((combinations, a, idx) => { + // create combination pairs + for (let i = 0; i < idx; i++) { + const b = chunks[i]; + combinations.push([b, a]); + } + return combinations; + }, []) + .filter(pair => { + // check if one of the chunks sizes is smaller than the minChunkSize + const p0SmallerThanMinChunkSize = + pair[0].size(equalOptions) < minChunkSize; + const p1SmallerThanMinChunkSize = + pair[1].size(equalOptions) < minChunkSize; + return p0SmallerThanMinChunkSize || p1SmallerThanMinChunkSize; + }) + .map(pair => { + // extend combination pairs with size and integrated size + const a = pair[0].size(options); + const b = pair[1].size(options); + const ab = pair[0].integratedSize(pair[1], options); + return [a + b - ab, ab, pair[0], pair[1]]; + }) + .filter(pair => { + // filter pairs that do not have an integratedSize + // meaning they can NOT be integrated! + return pair[1] !== false; + }) + .sort((a, b) => { + // sadly javascript does an inplace sort here + // sort by size + const diff = b[0] - a[0]; + if (diff !== 0) return diff; + return a[1] - b[1]; + }); + + if (sortedSizeFilteredExtendedPairCombinations.length === 0) return; + + const pair = sortedSizeFilteredExtendedPairCombinations[0]; + + pair[2].integrate(pair[3], "min-size"); + chunks.splice(chunks.indexOf(pair[3]), 1); + return true; + } + ); + }); + } +} +module.exports = MinChunkSizePlugin; diff --git a/node_modules/webpack/lib/optimize/ModuleConcatenationPlugin.js b/node_modules/webpack/lib/optimize/ModuleConcatenationPlugin.js index 8a6a660cb..15b7d796a 100644 --- a/node_modules/webpack/lib/optimize/ModuleConcatenationPlugin.js +++ b/node_modules/webpack/lib/optimize/ModuleConcatenationPlugin.js @@ -1,308 +1,483 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const HarmonyImportDependency = require("../dependencies/HarmonyImportDependency");
-const ModuleHotAcceptDependency = require("../dependencies/ModuleHotAcceptDependency");
-const ModuleHotDeclineDependency = require("../dependencies/ModuleHotDeclineDependency");
-const ConcatenatedModule = require("./ConcatenatedModule");
-const HarmonyExportImportedSpecifierDependency = require("../dependencies/HarmonyExportImportedSpecifierDependency");
-const HarmonyCompatibilityDependency = require("../dependencies/HarmonyCompatibilityDependency");
-
-function formatBailoutReason(msg) {
- return "ModuleConcatenation bailout: " + msg;
-}
-
-class ModuleConcatenationPlugin {
- constructor(options) {
- if(typeof options !== "object") options = {};
- this.options = options;
- }
-
- apply(compiler) {
- compiler.plugin("compilation", (compilation, params) => {
- params.normalModuleFactory.plugin("parser", (parser, parserOptions) => {
- parser.plugin("call eval", () => {
- parser.state.module.meta.hasEval = true;
- });
- });
- const bailoutReasonMap = new Map();
-
- function setBailoutReason(module, reason) {
- bailoutReasonMap.set(module, reason);
- module.optimizationBailout.push(typeof reason === "function" ? (rs) => formatBailoutReason(reason(rs)) : formatBailoutReason(reason));
- }
-
- function getBailoutReason(module, requestShortener) {
- const reason = bailoutReasonMap.get(module);
- if(typeof reason === "function") return reason(requestShortener);
- return reason;
- }
-
- compilation.plugin("optimize-chunk-modules", (chunks, modules) => {
- const relevantModules = [];
- const possibleInners = new Set();
- for(const module of modules) {
- // Only harmony modules are valid for optimization
- if(!module.meta || !module.meta.harmonyModule || !module.dependencies.some(d => d instanceof HarmonyCompatibilityDependency)) {
- setBailoutReason(module, "Module is not an ECMAScript module");
- continue;
- }
-
- // Because of variable renaming we can't use modules with eval
- if(module.meta && module.meta.hasEval) {
- setBailoutReason(module, "Module uses eval()");
- continue;
- }
-
- // Exports must be known (and not dynamic)
- if(!Array.isArray(module.providedExports)) {
- setBailoutReason(module, "Module exports are unknown");
- continue;
- }
-
- // Using dependency variables is not possible as this wraps the code in a function
- if(module.variables.length > 0) {
- setBailoutReason(module, `Module uses injected variables (${module.variables.map(v => v.name).join(", ")})`);
- continue;
- }
-
- // Hot Module Replacement need it's own module to work correctly
- if(module.dependencies.some(dep => dep instanceof ModuleHotAcceptDependency || dep instanceof ModuleHotDeclineDependency)) {
- setBailoutReason(module, "Module uses Hot Module Replacement");
- continue;
- }
-
- relevantModules.push(module);
-
- // Module must not be the entry points
- if(module.getChunks().some(chunk => chunk.entryModule === module)) {
- setBailoutReason(module, "Module is an entry point");
- continue;
- }
-
- // Module must only be used by Harmony Imports
- const nonHarmonyReasons = module.reasons.filter(reason => !(reason.dependency instanceof HarmonyImportDependency));
- if(nonHarmonyReasons.length > 0) {
- const importingModules = new Set(nonHarmonyReasons.map(r => r.module));
- const importingModuleTypes = new Map(Array.from(importingModules).map(m => [m, new Set(nonHarmonyReasons.filter(r => r.module === m).map(r => r.dependency.type).sort())]));
- setBailoutReason(module, (requestShortener) => {
- const names = Array.from(importingModules).map(m => `${m.readableIdentifier(requestShortener)} (referenced with ${Array.from(importingModuleTypes.get(m)).join(", ")})`).sort();
- return `Module is referenced from these modules with unsupported syntax: ${names.join(", ")}`;
- });
- continue;
- }
-
- possibleInners.add(module);
- }
- // sort by depth
- // modules with lower depth are more likely suited as roots
- // this improves performance, because modules already selected as inner are skipped
- relevantModules.sort((a, b) => {
- return a.depth - b.depth;
- });
- const concatConfigurations = [];
- const usedAsInner = new Set();
- for(const currentRoot of relevantModules) {
- // when used by another configuration as inner:
- // the other configuration is better and we can skip this one
- if(usedAsInner.has(currentRoot))
- continue;
-
- // create a configuration with the root
- const currentConfiguration = new ConcatConfiguration(currentRoot);
-
- // cache failures to add modules
- const failureCache = new Map();
-
- // try to add all imports
- for(const imp of this.getImports(currentRoot)) {
- const problem = this.tryToAdd(currentConfiguration, imp, possibleInners, failureCache);
- if(problem) {
- failureCache.set(imp, problem);
- currentConfiguration.addWarning(imp, problem);
- }
- }
- if(!currentConfiguration.isEmpty()) {
- concatConfigurations.push(currentConfiguration);
- for(const module of currentConfiguration.modules) {
- if(module !== currentConfiguration.rootModule)
- usedAsInner.add(module);
- }
- }
- }
- // HACK: Sort configurations by length and start with the longest one
- // to get the biggers groups possible. Used modules are marked with usedModules
- // TODO: Allow to reuse existing configuration while trying to add dependencies.
- // This would improve performance. O(n^2) -> O(n)
- concatConfigurations.sort((a, b) => {
- return b.modules.size - a.modules.size;
- });
- const usedModules = new Set();
- for(const concatConfiguration of concatConfigurations) {
- if(usedModules.has(concatConfiguration.rootModule))
- continue;
- const newModule = new ConcatenatedModule(concatConfiguration.rootModule, Array.from(concatConfiguration.modules));
- concatConfiguration.sortWarnings();
- for(const warning of concatConfiguration.warnings) {
- newModule.optimizationBailout.push((requestShortener) => {
- const reason = getBailoutReason(warning[0], requestShortener);
- const reasonWithPrefix = reason ? ` (<- ${reason})` : "";
- if(warning[0] === warning[1])
- return formatBailoutReason(`Cannot concat with ${warning[0].readableIdentifier(requestShortener)}${reasonWithPrefix}`);
- else
- return formatBailoutReason(`Cannot concat with ${warning[0].readableIdentifier(requestShortener)} because of ${warning[1].readableIdentifier(requestShortener)}${reasonWithPrefix}`);
- });
- }
- const chunks = concatConfiguration.rootModule.getChunks();
- for(const m of concatConfiguration.modules) {
- usedModules.add(m);
- chunks.forEach(chunk => chunk.removeModule(m));
- }
- chunks.forEach(chunk => {
- chunk.addModule(newModule);
- newModule.addChunk(chunk);
- if(chunk.entryModule === concatConfiguration.rootModule)
- chunk.entryModule = newModule;
- });
- compilation.modules.push(newModule);
- newModule.reasons.forEach(reason => reason.dependency.module = newModule);
- newModule.dependencies.forEach(dep => {
- if(dep.module) {
- dep.module.reasons.forEach(reason => {
- if(reason.dependency === dep)
- reason.module = newModule;
- });
- }
- });
- }
- compilation.modules = compilation.modules.filter(m => !usedModules.has(m));
- });
- });
- }
-
- getImports(module) {
- return Array.from(new Set(module.dependencies
-
- // Only harmony Dependencies
- .filter(dep => dep instanceof HarmonyImportDependency && dep.module)
-
- // Dependencies are simple enough to concat them
- .filter(dep => {
- return !module.dependencies.some(d =>
- d instanceof HarmonyExportImportedSpecifierDependency &&
- d.importDependency === dep &&
- !d.id &&
- !Array.isArray(dep.module.providedExports)
- );
- })
-
- // Take the imported module
- .map(dep => dep.module)
- ));
- }
-
- tryToAdd(config, module, possibleModules, failureCache) {
- const cacheEntry = failureCache.get(module);
- if(cacheEntry) {
- return cacheEntry;
- }
-
- // Already added?
- if(config.has(module)) {
- return null;
- }
-
- // Not possible to add?
- if(!possibleModules.has(module)) {
- failureCache.set(module, module); // cache failures for performance
- return module;
- }
-
- // module must be in the same chunks
- if(!config.rootModule.hasEqualsChunks(module)) {
- failureCache.set(module, module); // cache failures for performance
- return module;
- }
-
- // Clone config to make experimental changes
- const testConfig = config.clone();
-
- // Add the module
- testConfig.add(module);
-
- // Every module which depends on the added module must be in the configuration too.
- for(const reason of module.reasons) {
- const problem = this.tryToAdd(testConfig, reason.module, possibleModules, failureCache);
- if(problem) {
- failureCache.set(module, problem); // cache failures for performance
- return problem;
- }
- }
-
- // Eagerly try to add imports too if possible
- for(const imp of this.getImports(module)) {
- const problem = this.tryToAdd(testConfig, imp, possibleModules, failureCache);
- if(problem) {
- config.addWarning(module, problem);
- }
- }
-
- // Commit experimental changes
- config.set(testConfig);
- return null;
- }
-}
-
-class ConcatConfiguration {
- constructor(rootModule) {
- this.rootModule = rootModule;
- this.modules = new Set([rootModule]);
- this.warnings = new Map();
- }
-
- add(module) {
- this.modules.add(module);
- }
-
- has(module) {
- return this.modules.has(module);
- }
-
- isEmpty() {
- return this.modules.size === 1;
- }
-
- addWarning(module, problem) {
- this.warnings.set(module, problem);
- }
-
- sortWarnings() {
- this.warnings = new Map(Array.from(this.warnings).sort((a, b) => {
- const ai = a[0].identifier();
- const bi = b[0].identifier();
- if(ai < bi) return -1;
- if(ai > bi) return 1;
- return 0;
- }));
- }
-
- clone() {
- const clone = new ConcatConfiguration(this.rootModule);
- for(const module of this.modules)
- clone.add(module);
- for(const pair of this.warnings)
- clone.addWarning(pair[0], pair[1]);
- return clone;
- }
-
- set(config) {
- this.rootModule = config.rootModule;
- this.modules = new Set(config.modules);
- this.warnings = new Map(config.warnings);
- }
-}
-
-module.exports = ModuleConcatenationPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const HarmonyImportDependency = require("../dependencies/HarmonyImportDependency"); +const ModuleHotAcceptDependency = require("../dependencies/ModuleHotAcceptDependency"); +const ModuleHotDeclineDependency = require("../dependencies/ModuleHotDeclineDependency"); +const ConcatenatedModule = require("./ConcatenatedModule"); +const HarmonyCompatibilityDependency = require("../dependencies/HarmonyCompatibilityDependency"); +const StackedSetMap = require("../util/StackedSetMap"); + +const formatBailoutReason = msg => { + return "ModuleConcatenation bailout: " + msg; +}; + +class ModuleConcatenationPlugin { + constructor(options) { + if (typeof options !== "object") options = {}; + this.options = options; + } + + apply(compiler) { + compiler.hooks.compilation.tap( + "ModuleConcatenationPlugin", + (compilation, { normalModuleFactory }) => { + const handler = (parser, parserOptions) => { + parser.hooks.call.for("eval").tap("ModuleConcatenationPlugin", () => { + // Because of variable renaming we can't use modules with eval. + parser.state.module.buildMeta.moduleConcatenationBailout = "eval()"; + }); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("ModuleConcatenationPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("ModuleConcatenationPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("ModuleConcatenationPlugin", handler); + + const bailoutReasonMap = new Map(); + + const setBailoutReason = (module, reason) => { + bailoutReasonMap.set(module, reason); + module.optimizationBailout.push( + typeof reason === "function" + ? rs => formatBailoutReason(reason(rs)) + : formatBailoutReason(reason) + ); + }; + + const getBailoutReason = (module, requestShortener) => { + const reason = bailoutReasonMap.get(module); + if (typeof reason === "function") return reason(requestShortener); + return reason; + }; + + compilation.hooks.optimizeChunkModules.tap( + "ModuleConcatenationPlugin", + (chunks, modules) => { + const relevantModules = []; + const possibleInners = new Set(); + for (const module of modules) { + // Only harmony modules are valid for optimization + if ( + !module.buildMeta || + module.buildMeta.exportsType !== "namespace" || + !module.dependencies.some( + d => d instanceof HarmonyCompatibilityDependency + ) + ) { + setBailoutReason(module, "Module is not an ECMAScript module"); + continue; + } + + // Some expressions are not compatible with module concatenation + // because they may produce unexpected results. The plugin bails out + // if some were detected upfront. + if ( + module.buildMeta && + module.buildMeta.moduleConcatenationBailout + ) { + setBailoutReason( + module, + `Module uses ${module.buildMeta.moduleConcatenationBailout}` + ); + continue; + } + + // Exports must be known (and not dynamic) + if (!Array.isArray(module.buildMeta.providedExports)) { + setBailoutReason(module, "Module exports are unknown"); + continue; + } + + // Using dependency variables is not possible as this wraps the code in a function + if (module.variables.length > 0) { + setBailoutReason( + module, + `Module uses injected variables (${module.variables + .map(v => v.name) + .join(", ")})` + ); + continue; + } + + // Hot Module Replacement need it's own module to work correctly + if ( + module.dependencies.some( + dep => + dep instanceof ModuleHotAcceptDependency || + dep instanceof ModuleHotDeclineDependency + ) + ) { + setBailoutReason(module, "Module uses Hot Module Replacement"); + continue; + } + + relevantModules.push(module); + + // Module must not be the entry points + if (module.isEntryModule()) { + setBailoutReason(module, "Module is an entry point"); + continue; + } + + // Module must be in any chunk (we don't want to do useless work) + if (module.getNumberOfChunks() === 0) { + setBailoutReason(module, "Module is not in any chunk"); + continue; + } + + // Module must only be used by Harmony Imports + const nonHarmonyReasons = module.reasons.filter( + reason => + !reason.dependency || + !(reason.dependency instanceof HarmonyImportDependency) + ); + if (nonHarmonyReasons.length > 0) { + const importingModules = new Set( + nonHarmonyReasons.map(r => r.module).filter(Boolean) + ); + const importingExplanations = new Set( + nonHarmonyReasons.map(r => r.explanation).filter(Boolean) + ); + const importingModuleTypes = new Map( + Array.from(importingModules).map( + m => /** @type {[string, Set]} */ ([ + m, + new Set( + nonHarmonyReasons + .filter(r => r.module === m) + .map(r => r.dependency.type) + .sort() + ) + ]) + ) + ); + setBailoutReason(module, requestShortener => { + const names = Array.from(importingModules) + .map( + m => + `${m.readableIdentifier( + requestShortener + )} (referenced with ${Array.from( + importingModuleTypes.get(m) + ).join(", ")})` + ) + .sort(); + const explanations = Array.from(importingExplanations).sort(); + if (names.length > 0 && explanations.length === 0) { + return `Module is referenced from these modules with unsupported syntax: ${names.join( + ", " + )}`; + } else if (names.length === 0 && explanations.length > 0) { + return `Module is referenced by: ${explanations.join( + ", " + )}`; + } else if (names.length > 0 && explanations.length > 0) { + return `Module is referenced from these modules with unsupported syntax: ${names.join( + ", " + )} and by: ${explanations.join(", ")}`; + } else { + return "Module is referenced in a unsupported way"; + } + }); + continue; + } + + possibleInners.add(module); + } + // sort by depth + // modules with lower depth are more likely suited as roots + // this improves performance, because modules already selected as inner are skipped + relevantModules.sort((a, b) => { + return a.depth - b.depth; + }); + const concatConfigurations = []; + const usedAsInner = new Set(); + for (const currentRoot of relevantModules) { + // when used by another configuration as inner: + // the other configuration is better and we can skip this one + if (usedAsInner.has(currentRoot)) continue; + + // create a configuration with the root + const currentConfiguration = new ConcatConfiguration(currentRoot); + + // cache failures to add modules + const failureCache = new Map(); + + // try to add all imports + for (const imp of this._getImports(compilation, currentRoot)) { + const problem = this._tryToAdd( + compilation, + currentConfiguration, + imp, + possibleInners, + failureCache + ); + if (problem) { + failureCache.set(imp, problem); + currentConfiguration.addWarning(imp, problem); + } + } + if (!currentConfiguration.isEmpty()) { + concatConfigurations.push(currentConfiguration); + for (const module of currentConfiguration.getModules()) { + if (module !== currentConfiguration.rootModule) { + usedAsInner.add(module); + } + } + } + } + // HACK: Sort configurations by length and start with the longest one + // to get the biggers groups possible. Used modules are marked with usedModules + // TODO: Allow to reuse existing configuration while trying to add dependencies. + // This would improve performance. O(n^2) -> O(n) + concatConfigurations.sort((a, b) => { + return b.modules.size - a.modules.size; + }); + const usedModules = new Set(); + for (const concatConfiguration of concatConfigurations) { + if (usedModules.has(concatConfiguration.rootModule)) continue; + const modules = concatConfiguration.getModules(); + const rootModule = concatConfiguration.rootModule; + const newModule = new ConcatenatedModule( + rootModule, + Array.from(modules), + ConcatenatedModule.createConcatenationList( + rootModule, + modules, + compilation + ) + ); + for (const warning of concatConfiguration.getWarningsSorted()) { + newModule.optimizationBailout.push(requestShortener => { + const reason = getBailoutReason(warning[0], requestShortener); + const reasonWithPrefix = reason ? ` (<- ${reason})` : ""; + if (warning[0] === warning[1]) { + return formatBailoutReason( + `Cannot concat with ${warning[0].readableIdentifier( + requestShortener + )}${reasonWithPrefix}` + ); + } else { + return formatBailoutReason( + `Cannot concat with ${warning[0].readableIdentifier( + requestShortener + )} because of ${warning[1].readableIdentifier( + requestShortener + )}${reasonWithPrefix}` + ); + } + }); + } + const chunks = concatConfiguration.rootModule.getChunks(); + for (const m of modules) { + usedModules.add(m); + for (const chunk of chunks) { + chunk.removeModule(m); + } + } + for (const chunk of chunks) { + chunk.addModule(newModule); + newModule.addChunk(chunk); + if (chunk.entryModule === concatConfiguration.rootModule) { + chunk.entryModule = newModule; + } + } + compilation.modules.push(newModule); + for (const reason of newModule.reasons) { + if (reason.dependency.module === concatConfiguration.rootModule) + reason.dependency.module = newModule; + if ( + reason.dependency.redirectedModule === + concatConfiguration.rootModule + ) + reason.dependency.redirectedModule = newModule; + } + // TODO: remove when LTS node version contains fixed v8 version + // @see https://github.com/webpack/webpack/pull/6613 + // Turbofan does not correctly inline for-of loops with polymorphic input arrays. + // Work around issue by using a standard for loop and assigning dep.module.reasons + for (let i = 0; i < newModule.dependencies.length; i++) { + let dep = newModule.dependencies[i]; + if (dep.module) { + let reasons = dep.module.reasons; + for (let j = 0; j < reasons.length; j++) { + let reason = reasons[j]; + if (reason.dependency === dep) { + reason.module = newModule; + } + } + } + } + } + compilation.modules = compilation.modules.filter( + m => !usedModules.has(m) + ); + } + ); + } + ); + } + + _getImports(compilation, module) { + return new Set( + module.dependencies + + // Get reference info only for harmony Dependencies + .map(dep => { + if (!(dep instanceof HarmonyImportDependency)) return null; + if (!compilation) return dep.getReference(); + return compilation.getDependencyReference(module, dep); + }) + + // Reference is valid and has a module + // Dependencies are simple enough to concat them + .filter( + ref => + ref && + ref.module && + (Array.isArray(ref.importedNames) || + Array.isArray(ref.module.buildMeta.providedExports)) + ) + + // Take the imported module + .map(ref => ref.module) + ); + } + + _tryToAdd(compilation, config, module, possibleModules, failureCache) { + const cacheEntry = failureCache.get(module); + if (cacheEntry) { + return cacheEntry; + } + + // Already added? + if (config.has(module)) { + return null; + } + + // Not possible to add? + if (!possibleModules.has(module)) { + failureCache.set(module, module); // cache failures for performance + return module; + } + + // module must be in the same chunks + if (!config.rootModule.hasEqualsChunks(module)) { + failureCache.set(module, module); // cache failures for performance + return module; + } + + // Clone config to make experimental changes + const testConfig = config.clone(); + + // Add the module + testConfig.add(module); + + // Every module which depends on the added module must be in the configuration too. + for (const reason of module.reasons) { + // Modules that are not used can be ignored + if ( + reason.module.factoryMeta.sideEffectFree && + reason.module.used === false + ) + continue; + + const problem = this._tryToAdd( + compilation, + testConfig, + reason.module, + possibleModules, + failureCache + ); + if (problem) { + failureCache.set(module, problem); // cache failures for performance + return problem; + } + } + + // Commit experimental changes + config.set(testConfig); + + // Eagerly try to add imports too if possible + for (const imp of this._getImports(compilation, module)) { + const problem = this._tryToAdd( + compilation, + config, + imp, + possibleModules, + failureCache + ); + if (problem) { + config.addWarning(imp, problem); + } + } + return null; + } +} + +class ConcatConfiguration { + constructor(rootModule, cloneFrom) { + this.rootModule = rootModule; + if (cloneFrom) { + this.modules = cloneFrom.modules.createChild(5); + this.warnings = cloneFrom.warnings.createChild(5); + } else { + this.modules = new StackedSetMap(); + this.modules.add(rootModule); + this.warnings = new StackedSetMap(); + } + } + + add(module) { + this.modules.add(module); + } + + has(module) { + return this.modules.has(module); + } + + isEmpty() { + return this.modules.size === 1; + } + + addWarning(module, problem) { + this.warnings.set(module, problem); + } + + getWarningsSorted() { + return new Map( + this.warnings.asPairArray().sort((a, b) => { + const ai = a[0].identifier(); + const bi = b[0].identifier(); + if (ai < bi) return -1; + if (ai > bi) return 1; + return 0; + }) + ); + } + + getModules() { + return this.modules.asSet(); + } + + clone() { + return new ConcatConfiguration(this.rootModule, this); + } + + set(config) { + this.rootModule = config.rootModule; + this.modules = config.modules; + this.warnings = config.warnings; + } +} + +module.exports = ModuleConcatenationPlugin; diff --git a/node_modules/webpack/lib/optimize/OccurrenceOrderPlugin.js b/node_modules/webpack/lib/optimize/OccurrenceOrderPlugin.js index 45ec34719..c73ec8e57 100644 --- a/node_modules/webpack/lib/optimize/OccurrenceOrderPlugin.js +++ b/node_modules/webpack/lib/optimize/OccurrenceOrderPlugin.js @@ -1,102 +1,135 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-class OccurrenceOrderPlugin {
- constructor(preferEntry) {
- if(preferEntry !== undefined && typeof preferEntry !== "boolean") {
- throw new Error("Argument should be a boolean.\nFor more info on this plugin, see https://webpack.js.org/plugins/");
- }
- this.preferEntry = preferEntry;
- }
- apply(compiler) {
- const preferEntry = this.preferEntry;
- compiler.plugin("compilation", (compilation) => {
- compilation.plugin("optimize-module-order", (modules) => {
- const occursInInitialChunksMap = new Map();
- const occursInAllChunksMap = new Map();
-
- const initialChunkChunkMap = new Map();
- const entryCountMap = new Map();
- modules.forEach(m => {
- let initial = 0;
- let entry = 0;
- m.forEachChunk(c => {
- if(c.isInitial()) initial++;
- if(c.entryModule === m) entry++;
- });
- initialChunkChunkMap.set(m, initial);
- entryCountMap.set(m, entry);
- });
-
- const countOccursInEntry = (sum, r) => {
- if(!r.module) return sum;
- return sum + initialChunkChunkMap.get(r.module);
- };
- const countOccurs = (sum, r) => {
- if(!r.module) return sum;
- return sum + r.module.getNumberOfChunks();
- };
-
- if(preferEntry) {
- modules.forEach(m => {
- const result = m.reasons.reduce(countOccursInEntry, 0) + initialChunkChunkMap.get(m) + entryCountMap.get(m);
- occursInInitialChunksMap.set(m, result);
- });
- }
-
- modules.forEach(m => {
- const result = m.reasons.reduce(countOccurs, 0) + m.getNumberOfChunks() + entryCountMap.get(m);
- occursInAllChunksMap.set(m, result);
- });
-
- modules.sort((a, b) => {
- if(preferEntry) {
- const aEntryOccurs = occursInInitialChunksMap.get(a);
- const bEntryOccurs = occursInInitialChunksMap.get(b);
- if(aEntryOccurs > bEntryOccurs) return -1;
- if(aEntryOccurs < bEntryOccurs) return 1;
- }
- const aOccurs = occursInAllChunksMap.get(a);
- const bOccurs = occursInAllChunksMap.get(b);
- if(aOccurs > bOccurs) return -1;
- if(aOccurs < bOccurs) return 1;
- if(a.index > b.index) return 1;
- if(a.index < b.index) return -1;
- return 0;
- });
- });
- compilation.plugin("optimize-chunk-order", (chunks) => {
- const occursInInitialChunksMap = new Map();
-
- chunks.forEach(c => {
- const result = c.parents.reduce((sum, p) => {
- if(p.isInitial()) return sum + 1;
- return sum;
- }, 0);
- return occursInInitialChunksMap.set(c, result);
- });
-
- function occurs(c) {
- return c.blocks.length;
- }
-
- chunks.sort((a, b) => {
- const aEntryOccurs = occursInInitialChunksMap.get(a);
- const bEntryOccurs = occursInInitialChunksMap.get(b);
- if(aEntryOccurs > bEntryOccurs) return -1;
- if(aEntryOccurs < bEntryOccurs) return 1;
- const aOccurs = occurs(a);
- const bOccurs = occurs(b);
- if(aOccurs > bOccurs) return -1;
- if(aOccurs < bOccurs) return 1;
- return a.compareTo(b);
- });
- });
- });
- }
-}
-
-module.exports = OccurrenceOrderPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +// TODO webpack 5 remove this plugin +// It has been splitted into separate plugins for modules and chunks +class OccurrenceOrderPlugin { + constructor(preferEntry) { + if (preferEntry !== undefined && typeof preferEntry !== "boolean") { + throw new Error( + "Argument should be a boolean.\nFor more info on this plugin, see https://webpack.js.org/plugins/" + ); + } + this.preferEntry = preferEntry; + } + apply(compiler) { + const preferEntry = this.preferEntry; + compiler.hooks.compilation.tap("OccurrenceOrderPlugin", compilation => { + compilation.hooks.optimizeModuleOrder.tap( + "OccurrenceOrderPlugin", + modules => { + const occursInInitialChunksMap = new Map(); + const occursInAllChunksMap = new Map(); + + const initialChunkChunkMap = new Map(); + const entryCountMap = new Map(); + for (const m of modules) { + let initial = 0; + let entry = 0; + for (const c of m.chunksIterable) { + if (c.canBeInitial()) initial++; + if (c.entryModule === m) entry++; + } + initialChunkChunkMap.set(m, initial); + entryCountMap.set(m, entry); + } + + const countOccursInEntry = (sum, r) => { + if (!r.module) { + return sum; + } + return sum + initialChunkChunkMap.get(r.module); + }; + const countOccurs = (sum, r) => { + if (!r.module) { + return sum; + } + let factor = 1; + if (typeof r.dependency.getNumberOfIdOccurrences === "function") { + factor = r.dependency.getNumberOfIdOccurrences(); + } + if (factor === 0) { + return sum; + } + return sum + factor * r.module.getNumberOfChunks(); + }; + + if (preferEntry) { + for (const m of modules) { + const result = + m.reasons.reduce(countOccursInEntry, 0) + + initialChunkChunkMap.get(m) + + entryCountMap.get(m); + occursInInitialChunksMap.set(m, result); + } + } + + const originalOrder = new Map(); + let i = 0; + for (const m of modules) { + const result = + m.reasons.reduce(countOccurs, 0) + + m.getNumberOfChunks() + + entryCountMap.get(m); + occursInAllChunksMap.set(m, result); + originalOrder.set(m, i++); + } + + modules.sort((a, b) => { + if (preferEntry) { + const aEntryOccurs = occursInInitialChunksMap.get(a); + const bEntryOccurs = occursInInitialChunksMap.get(b); + if (aEntryOccurs > bEntryOccurs) return -1; + if (aEntryOccurs < bEntryOccurs) return 1; + } + const aOccurs = occursInAllChunksMap.get(a); + const bOccurs = occursInAllChunksMap.get(b); + if (aOccurs > bOccurs) return -1; + if (aOccurs < bOccurs) return 1; + const orgA = originalOrder.get(a); + const orgB = originalOrder.get(b); + return orgA - orgB; + }); + } + ); + compilation.hooks.optimizeChunkOrder.tap( + "OccurrenceOrderPlugin", + chunks => { + const occursInInitialChunksMap = new Map(); + const originalOrder = new Map(); + + let i = 0; + for (const c of chunks) { + let occurs = 0; + for (const chunkGroup of c.groupsIterable) { + for (const parent of chunkGroup.parentsIterable) { + if (parent.isInitial()) occurs++; + } + } + occursInInitialChunksMap.set(c, occurs); + originalOrder.set(c, i++); + } + + chunks.sort((a, b) => { + const aEntryOccurs = occursInInitialChunksMap.get(a); + const bEntryOccurs = occursInInitialChunksMap.get(b); + if (aEntryOccurs > bEntryOccurs) return -1; + if (aEntryOccurs < bEntryOccurs) return 1; + const aOccurs = a.getNumberOfGroups(); + const bOccurs = b.getNumberOfGroups(); + if (aOccurs > bOccurs) return -1; + if (aOccurs < bOccurs) return 1; + const orgA = originalOrder.get(a); + const orgB = originalOrder.get(b); + return orgA - orgB; + }); + } + ); + }); + } +} + +module.exports = OccurrenceOrderPlugin; diff --git a/node_modules/webpack/lib/optimize/RemoveEmptyChunksPlugin.js b/node_modules/webpack/lib/optimize/RemoveEmptyChunksPlugin.js index 4b75e4617..42ba24a15 100644 --- a/node_modules/webpack/lib/optimize/RemoveEmptyChunksPlugin.js +++ b/node_modules/webpack/lib/optimize/RemoveEmptyChunksPlugin.js @@ -1,21 +1,42 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-class RemoveEmptyChunksPlugin {
-
- apply(compiler) {
- compiler.plugin("compilation", (compilation) => {
- compilation.plugin(["optimize-chunks-basic", "optimize-extracted-chunks-basic"], (chunks) => {
- chunks.filter((chunk) => chunk.isEmpty() && !chunk.hasRuntime() && !chunk.hasEntryModule())
- .forEach((chunk) => {
- chunk.remove("empty");
- chunks.splice(chunks.indexOf(chunk), 1);
- });
- });
- });
- }
-}
-module.exports = RemoveEmptyChunksPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +class RemoveEmptyChunksPlugin { + apply(compiler) { + compiler.hooks.compilation.tap("RemoveEmptyChunksPlugin", compilation => { + const handler = chunks => { + for (let i = chunks.length - 1; i >= 0; i--) { + const chunk = chunks[i]; + if ( + chunk.isEmpty() && + !chunk.hasRuntime() && + !chunk.hasEntryModule() + ) { + chunk.remove("empty"); + chunks.splice(i, 1); + } + } + }; + compilation.hooks.optimizeChunksBasic.tap( + "RemoveEmptyChunksPlugin", + handler + ); + compilation.hooks.optimizeChunksAdvanced.tap( + "RemoveEmptyChunksPlugin", + handler + ); + compilation.hooks.optimizeExtractedChunksBasic.tap( + "RemoveEmptyChunksPlugin", + handler + ); + compilation.hooks.optimizeExtractedChunksAdvanced.tap( + "RemoveEmptyChunksPlugin", + handler + ); + }); + } +} +module.exports = RemoveEmptyChunksPlugin; diff --git a/node_modules/webpack/lib/optimize/RemoveParentModulesPlugin.js b/node_modules/webpack/lib/optimize/RemoveParentModulesPlugin.js index 43550819c..7fff59207 100644 --- a/node_modules/webpack/lib/optimize/RemoveParentModulesPlugin.js +++ b/node_modules/webpack/lib/optimize/RemoveParentModulesPlugin.js @@ -1,65 +1,127 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-function hasModule(chunk, module, checkedChunks) {
- if(chunk.containsModule(module)) return [chunk];
- if(chunk.parents.length === 0) return false;
- return allHaveModule(chunk.parents.filter((c) => {
- return !checkedChunks.has(c);
- }), module, checkedChunks);
-}
-
-function allHaveModule(someChunks, module, checkedChunks) {
- if(!checkedChunks) checkedChunks = new Set();
- var chunks = new Set();
- for(var i = 0; i < someChunks.length; i++) {
- checkedChunks.add(someChunks[i]);
- var subChunks = hasModule(someChunks[i], module, checkedChunks);
- if(!subChunks) return false;
-
- for(var index = 0; index < subChunks.length; index++) {
- var item = subChunks[index];
-
- chunks.add(item);
- }
- }
- return chunks;
-}
-
-class RemoveParentModulesPlugin {
- apply(compiler) {
- compiler.plugin("compilation", (compilation) => {
- compilation.plugin(["optimize-chunks-basic", "optimize-extracted-chunks-basic"], (chunks) => {
- for(var index = 0; index < chunks.length; index++) {
- var chunk = chunks[index];
- if(chunk.parents.length === 0) continue;
-
- // TODO consider Map when performance has improved https://gist.github.com/sokra/b36098368da7b8f6792fd7c85fca6311
- var cache = Object.create(null);
- var modules = chunk.getModules();
- for(var i = 0; i < modules.length; i++) {
- var module = modules[i];
-
- var dId = module.getChunkIdsIdent();
- var parentChunksWithModule;
- if(dId === null) {
- parentChunksWithModule = allHaveModule(chunk.parents, module);
- } else if(dId in cache) {
- parentChunksWithModule = cache[dId];
- } else {
- parentChunksWithModule = cache[dId] = allHaveModule(chunk.parents, module);
- }
- if(parentChunksWithModule) {
- module.rewriteChunkInReasons(chunk, Array.from(parentChunksWithModule));
- chunk.removeModule(module);
- }
- }
- }
- });
- });
- }
-}
-module.exports = RemoveParentModulesPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Queue = require("../util/Queue"); +const { intersect } = require("../util/SetHelpers"); + +const getParentChunksWithModule = (currentChunk, module) => { + const chunks = []; + const stack = new Set(currentChunk.parentsIterable); + + for (const chunk of stack) { + if (chunk.containsModule(module)) { + chunks.push(chunk); + } else { + for (const parent of chunk.parentsIterable) { + stack.add(parent); + } + } + } + + return chunks; +}; + +class RemoveParentModulesPlugin { + apply(compiler) { + compiler.hooks.compilation.tap("RemoveParentModulesPlugin", compilation => { + const handler = (chunks, chunkGroups) => { + const queue = new Queue(); + const availableModulesMap = new WeakMap(); + + for (const chunkGroup of compilation.entrypoints.values()) { + // initialize available modules for chunks without parents + availableModulesMap.set(chunkGroup, new Set()); + for (const child of chunkGroup.childrenIterable) { + queue.enqueue(child); + } + } + + while (queue.length > 0) { + const chunkGroup = queue.dequeue(); + let availableModules = availableModulesMap.get(chunkGroup); + let changed = false; + for (const parent of chunkGroup.parentsIterable) { + const availableModulesInParent = availableModulesMap.get(parent); + if (availableModulesInParent !== undefined) { + // If we know the available modules in parent: process these + if (availableModules === undefined) { + // if we have not own info yet: create new entry + availableModules = new Set(availableModulesInParent); + for (const chunk of parent.chunks) { + for (const m of chunk.modulesIterable) { + availableModules.add(m); + } + } + availableModulesMap.set(chunkGroup, availableModules); + changed = true; + } else { + for (const m of availableModules) { + if ( + !parent.containsModule(m) && + !availableModulesInParent.has(m) + ) { + availableModules.delete(m); + changed = true; + } + } + } + } + } + if (changed) { + // if something changed: enqueue our children + for (const child of chunkGroup.childrenIterable) { + queue.enqueue(child); + } + } + } + + // now we have available modules for every chunk + for (const chunk of chunks) { + const availableModulesSets = Array.from( + chunk.groupsIterable, + chunkGroup => availableModulesMap.get(chunkGroup) + ); + if (availableModulesSets.some(s => s === undefined)) continue; // No info about this chunk group + const availableModules = + availableModulesSets.length === 1 + ? availableModulesSets[0] + : intersect(availableModulesSets); + const numberOfModules = chunk.getNumberOfModules(); + const toRemove = new Set(); + if (numberOfModules < availableModules.size) { + for (const m of chunk.modulesIterable) { + if (availableModules.has(m)) { + toRemove.add(m); + } + } + } else { + for (const m of availableModules) { + if (chunk.containsModule(m)) { + toRemove.add(m); + } + } + } + for (const module of toRemove) { + module.rewriteChunkInReasons( + chunk, + getParentChunksWithModule(chunk, module) + ); + chunk.removeModule(module); + } + } + }; + compilation.hooks.optimizeChunksBasic.tap( + "RemoveParentModulesPlugin", + handler + ); + compilation.hooks.optimizeExtractedChunksBasic.tap( + "RemoveParentModulesPlugin", + handler + ); + }); + } +} +module.exports = RemoveParentModulesPlugin; diff --git a/node_modules/webpack/lib/optimize/UglifyJsPlugin.js b/node_modules/webpack/lib/optimize/UglifyJsPlugin.js deleted file mode 100644 index 1caa10817..000000000 --- a/node_modules/webpack/lib/optimize/UglifyJsPlugin.js +++ /dev/null @@ -1,9 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
-
-module.exports = UglifyJsPlugin;
diff --git a/node_modules/webpack/lib/performance/AssetsOverSizeLimitWarning.js b/node_modules/webpack/lib/performance/AssetsOverSizeLimitWarning.js index 17a5112d8..aac8b65a9 100644 --- a/node_modules/webpack/lib/performance/AssetsOverSizeLimitWarning.js +++ b/node_modules/webpack/lib/performance/AssetsOverSizeLimitWarning.js @@ -1,23 +1,30 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Sean Larkin @thelarkinn
-*/
-"use strict";
-
-const WebpackError = require("../WebpackError");
-const SizeFormatHelpers = require("../SizeFormatHelpers");
-
-module.exports = class AssetsOverSizeLimitWarning extends WebpackError {
- constructor(assetsOverSizeLimit, assetLimit) {
- super();
-
- this.name = "AssetsOverSizeLimitWarning";
- this.assets = assetsOverSizeLimit;
- const assetLists = this.assets.map(asset => `\n ${asset.name} (${SizeFormatHelpers.formatSize(asset.size)})`).join("");
- this.message = `asset size limit: The following asset(s) exceed the recommended size limit (${SizeFormatHelpers.formatSize(assetLimit)}).
-This can impact web performance.
-Assets: ${assetLists}`;
-
- Error.captureStackTrace(this, this.constructor);
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sean Larkin @thelarkinn +*/ +"use strict"; + +const WebpackError = require("../WebpackError"); +const SizeFormatHelpers = require("../SizeFormatHelpers"); + +module.exports = class AssetsOverSizeLimitWarning extends WebpackError { + constructor(assetsOverSizeLimit, assetLimit) { + const assetLists = assetsOverSizeLimit + .map( + asset => + `\n ${asset.name} (${SizeFormatHelpers.formatSize(asset.size)})` + ) + .join(""); + + super(`asset size limit: The following asset(s) exceed the recommended size limit (${SizeFormatHelpers.formatSize( + assetLimit + )}). +This can impact web performance. +Assets: ${assetLists}`); + + this.name = "AssetsOverSizeLimitWarning"; + this.assets = assetsOverSizeLimit; + + Error.captureStackTrace(this, this.constructor); + } +}; diff --git a/node_modules/webpack/lib/performance/EntrypointsOverSizeLimitWarning.js b/node_modules/webpack/lib/performance/EntrypointsOverSizeLimitWarning.js index 9fb2de104..3c29553d2 100644 --- a/node_modules/webpack/lib/performance/EntrypointsOverSizeLimitWarning.js +++ b/node_modules/webpack/lib/performance/EntrypointsOverSizeLimitWarning.js @@ -1,28 +1,30 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Sean Larkin @thelarkinn
-*/
-"use strict";
-
-const WebpackError = require("../WebpackError");
-const SizeFormatHelpers = require("../SizeFormatHelpers");
-
-module.exports = class EntrypointsOverSizeLimitWarning extends WebpackError {
- constructor(entrypoints, entrypointLimit) {
- super();
-
- this.name = "EntrypointsOverSizeLimitWarning";
- this.entrypoints = entrypoints;
- const entrypointList = this.entrypoints.map(entrypoint => `\n ${
- entrypoint.name
- } (${
- SizeFormatHelpers.formatSize(entrypoint.size)
- })\n${
- entrypoint.files.map(asset => ` ${asset}`).join("\n")
- }`).join("");
- this.message = `entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (${SizeFormatHelpers.formatSize(entrypointLimit)}). This can impact web performance.
-Entrypoints:${entrypointList}\n`;
-
- Error.captureStackTrace(this, this.constructor);
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sean Larkin @thelarkinn +*/ +"use strict"; + +const WebpackError = require("../WebpackError"); +const SizeFormatHelpers = require("../SizeFormatHelpers"); + +module.exports = class EntrypointsOverSizeLimitWarning extends WebpackError { + constructor(entrypoints, entrypointLimit) { + const entrypointList = entrypoints + .map( + entrypoint => + `\n ${entrypoint.name} (${SizeFormatHelpers.formatSize( + entrypoint.size + )})\n${entrypoint.files.map(asset => ` ${asset}`).join("\n")}` + ) + .join(""); + super(`entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (${SizeFormatHelpers.formatSize( + entrypointLimit + )}). This can impact web performance. +Entrypoints:${entrypointList}\n`); + + this.name = "EntrypointsOverSizeLimitWarning"; + this.entrypoints = entrypoints; + + Error.captureStackTrace(this, this.constructor); + } +}; diff --git a/node_modules/webpack/lib/performance/NoAsyncChunksWarning.js b/node_modules/webpack/lib/performance/NoAsyncChunksWarning.js index 2ca7c35b9..c64475f97 100644 --- a/node_modules/webpack/lib/performance/NoAsyncChunksWarning.js +++ b/node_modules/webpack/lib/performance/NoAsyncChunksWarning.js @@ -1,20 +1,21 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Sean Larkin @thelarkinn
-*/
-"use strict";
-
-const WebpackError = require("../WebpackError");
-
-module.exports = class NoAsyncChunksWarning extends WebpackError {
- constructor() {
- super();
-
- this.name = "NoAsyncChunksWarning";
- this.message = "webpack performance recommendations: \n" +
- "You can limit the size of your bundles by using import() or require.ensure to lazy load some parts of your application.\n" +
- "For more info visit https://webpack.js.org/guides/code-splitting/";
-
- Error.captureStackTrace(this, this.constructor);
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sean Larkin @thelarkinn +*/ +"use strict"; + +const WebpackError = require("../WebpackError"); + +module.exports = class NoAsyncChunksWarning extends WebpackError { + constructor() { + super( + "webpack performance recommendations: \n" + + "You can limit the size of your bundles by using import() or require.ensure to lazy load some parts of your application.\n" + + "For more info visit https://webpack.js.org/guides/code-splitting/" + ); + + this.name = "NoAsyncChunksWarning"; + + Error.captureStackTrace(this, this.constructor); + } +}; diff --git a/node_modules/webpack/lib/performance/SizeLimitsPlugin.js b/node_modules/webpack/lib/performance/SizeLimitsPlugin.js index e97b3b368..93b43651f 100644 --- a/node_modules/webpack/lib/performance/SizeLimitsPlugin.js +++ b/node_modules/webpack/lib/performance/SizeLimitsPlugin.js @@ -1,102 +1,105 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Sean Larkin @thelarkinn
-*/
-"use strict";
-const EntrypointsOverSizeLimitWarning = require("./EntrypointsOverSizeLimitWarning");
-const AssetsOverSizeLimitWarning = require("./AssetsOverSizeLimitWarning");
-const NoAsyncChunksWarning = require("./NoAsyncChunksWarning");
-
-module.exports = class SizeLimitsPlugin {
- constructor(options) {
- this.hints = options.hints;
- this.maxAssetSize = options.maxAssetSize;
- this.maxEntrypointSize = options.maxEntrypointSize;
- this.assetFilter = options.assetFilter;
- }
- apply(compiler) {
- const entrypointSizeLimit = this.maxEntrypointSize;
- const assetSizeLimit = this.maxAssetSize;
- const hints = this.hints;
- const assetFilter = this.assetFilter || (asset => !(/\.map$/.test(asset)));
-
- compiler.plugin("after-emit", (compilation, callback) => {
- const warnings = [];
-
- const getEntrypointSize = entrypoint =>
- entrypoint.getFiles()
- .filter(assetFilter)
- .map(file => compilation.assets[file])
- .filter(Boolean)
- .map(asset => asset.size())
- .reduce((currentSize, nextSize) => currentSize + nextSize, 0);
-
- const assetsOverSizeLimit = [];
- Object.keys(compilation.assets)
- .filter(assetFilter)
- .forEach(assetName => {
- const asset = compilation.assets[assetName];
- const size = asset.size();
-
- if(size > assetSizeLimit) {
- assetsOverSizeLimit.push({
- name: assetName,
- size: size,
- });
- asset.isOverSizeLimit = true;
- }
- });
-
- const entrypointsOverLimit = [];
- Object.keys(compilation.entrypoints)
- .forEach(key => {
- const entry = compilation.entrypoints[key];
- const size = getEntrypointSize(entry, compilation);
-
- if(size > entrypointSizeLimit) {
- entrypointsOverLimit.push({
- name: key,
- size: size,
- files: entry.getFiles().filter(assetFilter)
- });
- entry.isOverSizeLimit = true;
- }
- });
-
- if(hints) {
- // 1. Individual Chunk: Size < 250kb
- // 2. Collective Initial Chunks [entrypoint] (Each Set?): Size < 250kb
- // 3. No Async Chunks
- // if !1, then 2, if !2 return
- if(assetsOverSizeLimit.length > 0) {
- warnings.push(
- new AssetsOverSizeLimitWarning(
- assetsOverSizeLimit,
- assetSizeLimit));
- }
- if(entrypointsOverLimit.length > 0) {
- warnings.push(
- new EntrypointsOverSizeLimitWarning(
- entrypointsOverLimit,
- entrypointSizeLimit));
- }
-
- if(warnings.length > 0) {
- const hasAsyncChunks = compilation.chunks.filter(chunk => !chunk.isInitial()).length > 0;
-
- if(!hasAsyncChunks) {
- warnings.push(new NoAsyncChunksWarning());
- }
-
- if(hints === "error") {
- Array.prototype.push.apply(compilation.errors, warnings);
- } else {
- Array.prototype.push.apply(compilation.warnings, warnings);
- }
- }
- }
-
- callback();
- });
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sean Larkin @thelarkinn +*/ +"use strict"; +const EntrypointsOverSizeLimitWarning = require("./EntrypointsOverSizeLimitWarning"); +const AssetsOverSizeLimitWarning = require("./AssetsOverSizeLimitWarning"); +const NoAsyncChunksWarning = require("./NoAsyncChunksWarning"); + +module.exports = class SizeLimitsPlugin { + constructor(options) { + this.hints = options.hints; + this.maxAssetSize = options.maxAssetSize; + this.maxEntrypointSize = options.maxEntrypointSize; + this.assetFilter = options.assetFilter; + } + apply(compiler) { + const entrypointSizeLimit = this.maxEntrypointSize; + const assetSizeLimit = this.maxAssetSize; + const hints = this.hints; + const assetFilter = this.assetFilter || (asset => !asset.endsWith(".map")); + + compiler.hooks.afterEmit.tap("SizeLimitsPlugin", compilation => { + const warnings = []; + + const getEntrypointSize = entrypoint => + entrypoint.getFiles().reduce((currentSize, file) => { + if (assetFilter(file) && compilation.assets[file]) { + return currentSize + compilation.assets[file].size(); + } + + return currentSize; + }, 0); + + const assetsOverSizeLimit = []; + for (const assetName of Object.keys(compilation.assets)) { + if (!assetFilter(assetName)) { + continue; + } + + const asset = compilation.assets[assetName]; + const size = asset.size(); + if (size > assetSizeLimit) { + assetsOverSizeLimit.push({ + name: assetName, + size: size + }); + asset.isOverSizeLimit = true; + } + } + + const entrypointsOverLimit = []; + for (const pair of compilation.entrypoints) { + const name = pair[0]; + const entry = pair[1]; + const size = getEntrypointSize(entry); + + if (size > entrypointSizeLimit) { + entrypointsOverLimit.push({ + name: name, + size: size, + files: entry.getFiles().filter(assetFilter) + }); + entry.isOverSizeLimit = true; + } + } + + if (hints) { + // 1. Individual Chunk: Size < 250kb + // 2. Collective Initial Chunks [entrypoint] (Each Set?): Size < 250kb + // 3. No Async Chunks + // if !1, then 2, if !2 return + if (assetsOverSizeLimit.length > 0) { + warnings.push( + new AssetsOverSizeLimitWarning(assetsOverSizeLimit, assetSizeLimit) + ); + } + if (entrypointsOverLimit.length > 0) { + warnings.push( + new EntrypointsOverSizeLimitWarning( + entrypointsOverLimit, + entrypointSizeLimit + ) + ); + } + + if (warnings.length > 0) { + const hasAsyncChunks = + compilation.chunks.filter(chunk => !chunk.canBeInitial()).length > + 0; + + if (!hasAsyncChunks) { + warnings.push(new NoAsyncChunksWarning()); + } + + if (hints === "error") { + compilation.errors.push(...warnings); + } else { + compilation.warnings.push(...warnings); + } + } + } + }); + } +}; diff --git a/node_modules/webpack/lib/prepareOptions.js b/node_modules/webpack/lib/prepareOptions.js deleted file mode 100644 index 0b063a03b..000000000 --- a/node_modules/webpack/lib/prepareOptions.js +++ /dev/null @@ -1,29 +0,0 @@ -"use strict";
-
-module.exports = function prepareOptions(options, argv) {
- argv = argv || {};
-
- options = handleExport(options);
-
- if(Array.isArray(options)) {
- options = options.map(_options => handleFunction(_options, argv));
- } else {
- options = handleFunction(options, argv);
- }
- return options;
-};
-
-function handleExport(options) {
- const isES6DefaultExported = (
- typeof options === "object" && options !== null && typeof options.default !== "undefined"
- );
- options = isES6DefaultExported ? options.default : options;
- return options;
-}
-
-function handleFunction(options, argv) {
- if(typeof options === "function") {
- options = options(argv.env, argv);
- }
- return options;
-}
diff --git a/node_modules/webpack/lib/removeAndDo.js b/node_modules/webpack/lib/removeAndDo.js deleted file mode 100644 index a857d8a32..000000000 --- a/node_modules/webpack/lib/removeAndDo.js +++ /dev/null @@ -1,15 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-module.exports = function removeAndDo(collection, thing, action) {
- const idx = this[collection].indexOf(thing);
- const hasThingInCollection = idx >= 0;
- if(hasThingInCollection) {
- this[collection].splice(idx, 1);
- thing[action](this);
- }
- return hasThingInCollection;
-};
diff --git a/node_modules/webpack/lib/util/Queue.js b/node_modules/webpack/lib/util/Queue.js index ef3ffdc80..6615e9f77 100644 --- a/node_modules/webpack/lib/util/Queue.js +++ b/node_modules/webpack/lib/util/Queue.js @@ -1,42 +1,46 @@ -"use strict";
-
-module.exports = class Queue {
- constructor(items) {
- this.first = null;
- this.last = null;
- this.length = 0;
- if(items) {
- for(const item of items) {
- this.enqueue(item);
- }
- }
- }
-
- enqueue(item) {
- const first = this.first;
- const node = {
- item,
- next: null
- };
- if(first === null) {
- this.last = node;
- } else {
- first.next = node;
- }
- this.first = node;
- this.length++;
- }
-
- dequeue() {
- const last = this.last;
- if(last === null)
- return undefined;
- const next = last.next;
- if(next === null) {
- this.first = null;
- }
- this.last = next;
- this.length--;
- return last.item;
- }
-};
+"use strict"; + +/** + * @template T + */ +class Queue { + /** + * @param {Iterable<T>=} items The initial elements. + */ + constructor(items) { + /** @private @type {Set<T>} */ + this.set = new Set(items); + /** @private @type {Iterator<T>} */ + this.iterator = this.set[Symbol.iterator](); + } + + /** + * Returns the number of elements in this queue. + * @returns {number} The number of elements in this queue. + */ + get length() { + return this.set.size; + } + + /** + * Appends the specified element to this queue. + * @param {T} item The element to add. + * @returns {void} + */ + enqueue(item) { + this.set.add(item); + } + + /** + * Retrieves and removes the head of this queue. + * @returns {T | undefined} The head of the queue of `undefined` if this queue is empty. + */ + dequeue() { + const result = this.iterator.next(); + if (result.done) return undefined; + this.set.delete(result.value); + return result.value; + } +} + +module.exports = Queue; diff --git a/node_modules/webpack/lib/util/Semaphore.js b/node_modules/webpack/lib/util/Semaphore.js index de9b69dde..d6c876651 100644 --- a/node_modules/webpack/lib/util/Semaphore.js +++ b/node_modules/webpack/lib/util/Semaphore.js @@ -1,32 +1,53 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-class Semaphore {
- constructor(available) {
- this.available = available;
- this.waiters = [];
- }
-
- acquire(callback) {
- if(this.available > 0) {
- this.available--;
- callback();
- } else {
- this.waiters.push(callback);
- }
- }
-
- release() {
- if(this.waiters.length > 0) {
- const callback = this.waiters.pop();
- process.nextTick(callback);
- } else {
- this.available++;
- }
- }
-}
-
-module.exports = Semaphore;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +class Semaphore { + /** + * Creates an instance of Semaphore. + * + * @param {number} available the amount available number of "tasks" + * in the Semaphore + */ + constructor(available) { + this.available = available; + /** @type {(function(): void)[]} */ + this.waiters = []; + /** @private */ + this._continue = this._continue.bind(this); + } + + /** + * @param {function(): void} callback function block to capture and run + * @returns {void} + */ + acquire(callback) { + if (this.available > 0) { + this.available--; + callback(); + } else { + this.waiters.push(callback); + } + } + + release() { + this.available++; + if (this.waiters.length > 0) { + process.nextTick(this._continue); + } + } + + _continue() { + if (this.available > 0) { + if (this.waiters.length > 0) { + this.available--; + const callback = this.waiters.pop(); + callback(); + } + } + } +} + +module.exports = Semaphore; diff --git a/node_modules/webpack/lib/util/SortableSet.js b/node_modules/webpack/lib/util/SortableSet.js index 15c7ecb87..44b692f37 100644 --- a/node_modules/webpack/lib/util/SortableSet.js +++ b/node_modules/webpack/lib/util/SortableSet.js @@ -1,45 +1,140 @@ -"use strict";
-
-module.exports = class SortableSet extends Set {
-
- constructor(initialIterable, defaultSort) {
- super(initialIterable);
- this._sortFn = defaultSort;
- this._lastActiveSortFn = null;
- }
-
- /**
- * @param {any} value - value to add to set
- * @returns {SortableSet} - returns itself
- */
- add(value) {
- this._lastActiveSortFn = null;
- super.add(value);
- return this;
- }
-
- /**
- * @param {Function} sortFn - function to sort the set
- * @returns {void}
- */
- sortWith(sortFn) {
- if(this.size === 0 || sortFn === this._lastActiveSortFn) {
- // already sorted - nothing to do
- return;
- }
-
- const sortedArray = Array.from(this).sort(sortFn);
- super.clear();
- for(let i = 0; i < sortedArray.length; i += 1) {
- this.add(sortedArray[i]);
- }
- this._lastActiveSortFn = sortFn;
- }
-
- /**
- * @returns {void}
- */
- sort() {
- this.sortWith(this._sortFn);
- }
-};
+"use strict"; + +/** + * A subset of Set that offers sorting functionality + * @template T item type in set + * @extends {Set<T>} + */ +class SortableSet extends Set { + /** + * Create a new sortable set + * @param {Iterable<T>=} initialIterable The initial iterable value + * @typedef {function(T, T): number} SortFunction + * @param {SortFunction=} defaultSort Default sorting function + */ + constructor(initialIterable, defaultSort) { + super(initialIterable); + /** @private @type {function(T, T): number}} */ + this._sortFn = defaultSort; + /** @private @type {function(T, T): number} | null} */ + this._lastActiveSortFn = null; + /** @private @type {Map<Function, T[]> | undefined} */ + this._cache = undefined; + /** @private @type {Map<Function, T[]|string|number> | undefined} */ + this._cacheOrderIndependent = undefined; + } + + /** + * @param {T} value value to add to set + * @returns {this} returns itself + */ + add(value) { + this._lastActiveSortFn = null; + this._invalidateCache(); + this._invalidateOrderedCache(); + super.add(value); + return this; + } + + /** + * @param {T} value value to delete + * @returns {boolean} true if value existed in set, false otherwise + */ + delete(value) { + this._invalidateCache(); + this._invalidateOrderedCache(); + return super.delete(value); + } + + /** + * @returns {void} + */ + clear() { + this._invalidateCache(); + this._invalidateOrderedCache(); + return super.clear(); + } + + /** + * Sort with a comparer function + * @param {SortFunction} sortFn Sorting comparer function + * @returns {void} + */ + sortWith(sortFn) { + if (this.size <= 1 || sortFn === this._lastActiveSortFn) { + // already sorted - nothing to do + return; + } + + const sortedArray = Array.from(this).sort(sortFn); + super.clear(); + for (let i = 0; i < sortedArray.length; i += 1) { + super.add(sortedArray[i]); + } + this._lastActiveSortFn = sortFn; + this._invalidateCache(); + } + + sort() { + this.sortWith(this._sortFn); + } + + /** + * Get data from cache + * @param {function(SortableSet<T>): T[]} fn function to calculate value + * @returns {T[]} returns result of fn(this), cached until set changes + */ + getFromCache(fn) { + if (this._cache === undefined) { + this._cache = new Map(); + } else { + const data = this._cache.get(fn); + if (data !== undefined) { + return data; + } + } + const newData = fn(this); + this._cache.set(fn, newData); + return newData; + } + + /** + * @param {function(SortableSet<T>): string|number|T[]} fn function to calculate value + * @returns {any} returns result of fn(this), cached until set changes + */ + getFromUnorderedCache(fn) { + if (this._cacheOrderIndependent === undefined) { + this._cacheOrderIndependent = new Map(); + } else { + const data = this._cacheOrderIndependent.get(fn); + if (data !== undefined) { + return data; + } + } + const newData = fn(this); + this._cacheOrderIndependent.set(fn, newData); + return newData; + } + + /** + * @private + * @returns {void} + */ + _invalidateCache() { + if (this._cache !== undefined) { + this._cache.clear(); + } + } + + /** + * @private + * @returns {void} + */ + _invalidateOrderedCache() { + if (this._cacheOrderIndependent !== undefined) { + this._cacheOrderIndependent.clear(); + } + } +} + +module.exports = SortableSet; diff --git a/node_modules/webpack/lib/util/identifier.js b/node_modules/webpack/lib/util/identifier.js index 82e5b811f..186bc064e 100644 --- a/node_modules/webpack/lib/util/identifier.js +++ b/node_modules/webpack/lib/util/identifier.js @@ -1,38 +1,103 @@ -"use strict";
-const path = require("path");
-
-const looksLikeAbsolutePath = (maybeAbsolutePath) => {
- return /^(?:[a-z]:\\|\/)/i.test(maybeAbsolutePath);
-};
-
-const normalizePathSeparator = (p) => p.replace(/\\/g, "/");
-
-const _makePathsRelative = (context, identifier) => {
- return identifier
- .split(/([|! ])/)
- .map(str => looksLikeAbsolutePath(str) ?
- normalizePathSeparator(path.relative(context, str)) : str)
- .join("");
-};
-
-exports.makePathsRelative = (context, identifier, cache) => {
- if(!cache) return _makePathsRelative(context, identifier);
-
- const relativePaths = cache.relativePaths || (cache.relativePaths = new Map());
-
- let cachedResult;
- let contextCache = relativePaths.get(context);
- if(typeof contextCache === "undefined") {
- relativePaths.set(context, contextCache = new Map());
- } else {
- cachedResult = contextCache.get(identifier);
- }
-
- if(typeof cachedResult !== "undefined") {
- return cachedResult;
- } else {
- const relativePath = _makePathsRelative(context, identifier);
- contextCache.set(identifier, relativePath);
- return relativePath;
- }
-};
+"use strict"; +const path = require("path"); + +/** + * @typedef {Object} MakeRelativePathsCache + * @property {Map<string, Map<string, string>>=} relativePaths + */ + +/** + * + * @param {string} maybeAbsolutePath path to check + * @returns {boolean} returns true if path is "Absolute Path"-like + */ +const looksLikeAbsolutePath = maybeAbsolutePath => { + if (/^\/.*\/$/.test(maybeAbsolutePath)) { + // this 'path' is actually a regexp generated by dynamic requires. + // Don't treat it as an absolute path. + return false; + } + return /^(?:[a-z]:\\|\/)/i.test(maybeAbsolutePath); +}; + +/** + * + * @param {string} p path to normalize + * @returns {string} normalized version of path + */ +const normalizePathSeparator = p => p.replace(/\\/g, "/"); + +/** + * + * @param {string} context context for relative path + * @param {string} identifier identifier for path + * @returns {string} a converted relative path + */ +const _makePathsRelative = (context, identifier) => { + return identifier + .split(/([|! ])/) + .map( + str => + looksLikeAbsolutePath(str) + ? normalizePathSeparator(path.relative(context, str)) + : str + ) + .join(""); +}; + +/** + * + * @param {string} context context used to create relative path + * @param {string} identifier identifier used to create relative path + * @param {MakeRelativePathsCache=} cache the cache object being set + * @returns {string} the returned relative path + */ +exports.makePathsRelative = (context, identifier, cache) => { + if (!cache) return _makePathsRelative(context, identifier); + + const relativePaths = + cache.relativePaths || (cache.relativePaths = new Map()); + + let cachedResult; + let contextCache = relativePaths.get(context); + if (contextCache === undefined) { + relativePaths.set(context, (contextCache = new Map())); + } else { + cachedResult = contextCache.get(identifier); + } + + if (cachedResult !== undefined) { + return cachedResult; + } else { + const relativePath = _makePathsRelative(context, identifier); + contextCache.set(identifier, relativePath); + return relativePath; + } +}; + +/** + * @param {string} context absolute context path + * @param {string} request any request string may containing absolute paths, query string, etc. + * @returns {string} a new request string avoiding absolute paths when possible + */ +exports.contextify = (context, request) => { + return request + .split("!") + .map(r => { + const splitPath = r.split("?", 2); + if (/^[a-zA-Z]:\\/.test(splitPath[0])) { + splitPath[0] = path.win32.relative(context, splitPath[0]); + if (!/^[a-zA-Z]:\\/.test(splitPath[0])) { + splitPath[0] = splitPath[0].replace(/\\/g, "/"); + } + } + if (/^\//.test(splitPath[0])) { + splitPath[0] = path.posix.relative(context, splitPath[0]); + } + if (!/^(\.\.\/|\/|[a-zA-Z]:\\)/.test(splitPath[0])) { + splitPath[0] = "./" + splitPath[0]; + } + return splitPath.join("?"); + }) + .join("!"); +}; diff --git a/node_modules/webpack/lib/validateSchema.js b/node_modules/webpack/lib/validateSchema.js index 8d415c170..b748c2c8f 100644 --- a/node_modules/webpack/lib/validateSchema.js +++ b/node_modules/webpack/lib/validateSchema.js @@ -1,66 +1,67 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Gajus Kuizinas @gajus
-*/
-"use strict";
-
-const Ajv = require("ajv");
-const ajv = new Ajv({
- errorDataPath: "configuration",
- allErrors: true,
- verbose: true
-});
-require("ajv-keywords")(ajv, ["instanceof"]);
-require("../schemas/ajv.absolutePath")(ajv);
-
-function validateSchema(schema, options) {
- if(Array.isArray(options)) {
- const errors = options.map((options) => validateObject(schema, options));
- errors.forEach((list, idx) => {
- list.forEach(function applyPrefix(err) {
- err.dataPath = `[${idx}]${err.dataPath}`;
- if(err.children) {
- err.children.forEach(applyPrefix);
- }
- });
- });
- return errors.reduce((arr, items) => {
- return arr.concat(items);
- }, []);
- } else {
- return validateObject(schema, options);
- }
-}
-
-function validateObject(schema, options) {
- const validate = ajv.compile(schema);
- const valid = validate(options);
- return valid ? [] : filterErrors(validate.errors);
-}
-
-function filterErrors(errors) {
- let newErrors = [];
- errors.forEach((err) => {
- const dataPath = err.dataPath;
- let children = [];
- newErrors = newErrors.filter((oldError) => {
- if(oldError.dataPath.includes(dataPath)) {
- if(oldError.children) {
- children = children.concat(oldError.children.slice(0));
- }
- oldError.children = undefined;
- children.push(oldError);
- return false;
- }
- return true;
- });
- if(children.length) {
- err.children = children;
- }
- newErrors.push(err);
- });
-
- return newErrors;
-}
-
-module.exports = validateSchema;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Gajus Kuizinas @gajus +*/ +"use strict"; + +const Ajv = require("ajv"); +const ajv = new Ajv({ + errorDataPath: "configuration", + allErrors: true, + verbose: true +}); +require("ajv-keywords")(ajv, ["instanceof"]); +require("../schemas/ajv.absolutePath")(ajv); + +const validateSchema = (schema, options) => { + if (Array.isArray(options)) { + const errors = options.map(options => validateObject(schema, options)); + errors.forEach((list, idx) => { + const applyPrefix = err => { + err.dataPath = `[${idx}]${err.dataPath}`; + if (err.children) { + err.children.forEach(applyPrefix); + } + }; + list.forEach(applyPrefix); + }); + return errors.reduce((arr, items) => { + return arr.concat(items); + }, []); + } else { + return validateObject(schema, options); + } +}; + +const validateObject = (schema, options) => { + const validate = ajv.compile(schema); + const valid = validate(options); + return valid ? [] : filterErrors(validate.errors); +}; + +const filterErrors = errors => { + let newErrors = []; + for (const err of errors) { + const dataPath = err.dataPath; + let children = []; + newErrors = newErrors.filter(oldError => { + if (oldError.dataPath.includes(dataPath)) { + if (oldError.children) { + children = children.concat(oldError.children.slice(0)); + } + oldError.children = undefined; + children.push(oldError); + return false; + } + return true; + }); + if (children.length) { + err.children = children; + } + newErrors.push(err); + } + + return newErrors; +}; + +module.exports = validateSchema; diff --git a/node_modules/webpack/lib/web/WebEnvironmentPlugin.js b/node_modules/webpack/lib/web/WebEnvironmentPlugin.js index 46e783bbb..9b0df5746 100644 --- a/node_modules/webpack/lib/web/WebEnvironmentPlugin.js +++ b/node_modules/webpack/lib/web/WebEnvironmentPlugin.js @@ -1,18 +1,18 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-class WebEnvironmentPlugin {
- constructor(inputFileSystem, outputFileSystem) {
- this.inputFileSystem = inputFileSystem;
- this.outputFileSystem = outputFileSystem;
- }
-
- apply(compiler) {
- compiler.outputFileSystem = this.outputFileSystem;
- }
-}
-
-module.exports = WebEnvironmentPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +class WebEnvironmentPlugin { + constructor(inputFileSystem, outputFileSystem) { + this.inputFileSystem = inputFileSystem; + this.outputFileSystem = outputFileSystem; + } + + apply(compiler) { + compiler.outputFileSystem = this.outputFileSystem; + } +} + +module.exports = WebEnvironmentPlugin; diff --git a/node_modules/webpack/lib/webpack.js b/node_modules/webpack/lib/webpack.js index 81fc7d83f..61357818e 100644 --- a/node_modules/webpack/lib/webpack.js +++ b/node_modules/webpack/lib/webpack.js @@ -1,120 +1,191 @@ -/*
- 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 NodeEnvironmentPlugin = require("./node/NodeEnvironmentPlugin");
-const WebpackOptionsApply = require("./WebpackOptionsApply");
-const WebpackOptionsDefaulter = require("./WebpackOptionsDefaulter");
-const validateSchema = require("./validateSchema");
-const WebpackOptionsValidationError = require("./WebpackOptionsValidationError");
-const webpackOptionsSchema = require("../schemas/webpackOptionsSchema.json");
-
-function webpack(options, callback) {
- const webpackOptionsValidationErrors = validateSchema(webpackOptionsSchema, options);
- if(webpackOptionsValidationErrors.length) {
- throw new WebpackOptionsValidationError(webpackOptionsValidationErrors);
- }
- let compiler;
- if(Array.isArray(options)) {
- compiler = new MultiCompiler(options.map(options => webpack(options)));
- } else if(typeof options === "object") {
- // TODO webpack 4: process returns options
- new WebpackOptionsDefaulter().process(options);
-
- compiler = new Compiler();
- compiler.context = options.context;
- compiler.options = options;
- new NodeEnvironmentPlugin().apply(compiler);
- if(options.plugins && Array.isArray(options.plugins)) {
- compiler.apply.apply(compiler, options.plugins);
- }
- compiler.applyPlugins("environment");
- compiler.applyPlugins("after-environment");
- compiler.options = new WebpackOptionsApply().process(options, compiler);
- } else {
- throw new Error("Invalid argument: options");
- }
- if(callback) {
- if(typeof callback !== "function") throw new Error("Invalid argument: callback");
- if(options.watch === true || (Array.isArray(options) && options.some(o => o.watch))) {
- const watchOptions = Array.isArray(options) ? options.map(o => o.watchOptions || {}) : (options.watchOptions || {});
- return compiler.watch(watchOptions, callback);
- }
- compiler.run(callback);
- }
- return compiler;
-}
-exports = module.exports = webpack;
-
-webpack.WebpackOptionsDefaulter = WebpackOptionsDefaulter;
-webpack.WebpackOptionsApply = WebpackOptionsApply;
-webpack.Compiler = Compiler;
-webpack.MultiCompiler = MultiCompiler;
-webpack.NodeEnvironmentPlugin = NodeEnvironmentPlugin;
-webpack.validate = validateSchema.bind(this, webpackOptionsSchema);
-webpack.validateSchema = validateSchema;
-webpack.WebpackOptionsValidationError = WebpackOptionsValidationError;
-
-function exportPlugins(obj, mappings) {
- Object.keys(mappings).forEach(name => {
- Object.defineProperty(obj, name, {
- configurable: false,
- enumerable: true,
- get: mappings[name]
- });
- });
-}
-
-exportPlugins(exports, {
- "DefinePlugin": () => require("./DefinePlugin"),
- "NormalModuleReplacementPlugin": () => require("./NormalModuleReplacementPlugin"),
- "ContextReplacementPlugin": () => require("./ContextReplacementPlugin"),
- "ContextExclusionPlugin": () => require("./ContextExclusionPlugin"),
- "IgnorePlugin": () => require("./IgnorePlugin"),
- "WatchIgnorePlugin": () => require("./WatchIgnorePlugin"),
- "BannerPlugin": () => require("./BannerPlugin"),
- "PrefetchPlugin": () => require("./PrefetchPlugin"),
- "AutomaticPrefetchPlugin": () => require("./AutomaticPrefetchPlugin"),
- "ProvidePlugin": () => require("./ProvidePlugin"),
- "HotModuleReplacementPlugin": () => require("./HotModuleReplacementPlugin"),
- "SourceMapDevToolPlugin": () => require("./SourceMapDevToolPlugin"),
- "EvalSourceMapDevToolPlugin": () => require("./EvalSourceMapDevToolPlugin"),
- "EvalDevToolModulePlugin": () => require("./EvalDevToolModulePlugin"),
- "CachePlugin": () => require("./CachePlugin"),
- "ExtendedAPIPlugin": () => require("./ExtendedAPIPlugin"),
- "ExternalsPlugin": () => require("./ExternalsPlugin"),
- "JsonpTemplatePlugin": () => require("./JsonpTemplatePlugin"),
- "LibraryTemplatePlugin": () => require("./LibraryTemplatePlugin"),
- "LoaderTargetPlugin": () => require("./LoaderTargetPlugin"),
- "MemoryOutputFileSystem": () => require("./MemoryOutputFileSystem"),
- "ProgressPlugin": () => require("./ProgressPlugin"),
- "SetVarMainTemplatePlugin": () => require("./SetVarMainTemplatePlugin"),
- "UmdMainTemplatePlugin": () => require("./UmdMainTemplatePlugin"),
- "NoErrorsPlugin": () => require("./NoErrorsPlugin"),
- "NoEmitOnErrorsPlugin": () => require("./NoEmitOnErrorsPlugin"),
- "NewWatchingPlugin": () => require("./NewWatchingPlugin"),
- "EnvironmentPlugin": () => require("./EnvironmentPlugin"),
- "DllPlugin": () => require("./DllPlugin"),
- "DllReferencePlugin": () => require("./DllReferencePlugin"),
- "LoaderOptionsPlugin": () => require("./LoaderOptionsPlugin"),
- "NamedModulesPlugin": () => require("./NamedModulesPlugin"),
- "NamedChunksPlugin": () => require("./NamedChunksPlugin"),
- "HashedModuleIdsPlugin": () => require("./HashedModuleIdsPlugin"),
- "ModuleFilenameHelpers": () => require("./ModuleFilenameHelpers")
-});
-exportPlugins(exports.optimize = {}, {
- "AggressiveMergingPlugin": () => require("./optimize/AggressiveMergingPlugin"),
- "AggressiveSplittingPlugin": () => require("./optimize/AggressiveSplittingPlugin"),
- "CommonsChunkPlugin": () => require("./optimize/CommonsChunkPlugin"),
- "ChunkModuleIdRangePlugin": () => require("./optimize/ChunkModuleIdRangePlugin"),
- "DedupePlugin": () => require("./optimize/DedupePlugin"),
- "LimitChunkCountPlugin": () => require("./optimize/LimitChunkCountPlugin"),
- "MinChunkSizePlugin": () => require("./optimize/MinChunkSizePlugin"),
- "ModuleConcatenationPlugin": () => require("./optimize/ModuleConcatenationPlugin"),
- "OccurrenceOrderPlugin": () => require("./optimize/OccurrenceOrderPlugin"),
- "UglifyJsPlugin": () => require("./optimize/UglifyJsPlugin")
-});
+/* + 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 NodeEnvironmentPlugin = require("./node/NodeEnvironmentPlugin"); +const WebpackOptionsApply = require("./WebpackOptionsApply"); +const WebpackOptionsDefaulter = require("./WebpackOptionsDefaulter"); +const validateSchema = require("./validateSchema"); +const WebpackOptionsValidationError = require("./WebpackOptionsValidationError"); +const webpackOptionsSchema = require("../schemas/WebpackOptions.json"); +const RemovedPluginError = require("./RemovedPluginError"); +const version = require("../package.json").version; + +const webpack = (options, callback) => { + const webpackOptionsValidationErrors = validateSchema( + webpackOptionsSchema, + options + ); + if (webpackOptionsValidationErrors.length) { + throw new WebpackOptionsValidationError(webpackOptionsValidationErrors); + } + let compiler; + if (Array.isArray(options)) { + compiler = new MultiCompiler(options.map(options => webpack(options))); + } else if (typeof options === "object") { + options = new WebpackOptionsDefaulter().process(options); + + compiler = new Compiler(options.context); + compiler.options = options; + new NodeEnvironmentPlugin().apply(compiler); + if (options.plugins && Array.isArray(options.plugins)) { + for (const plugin of options.plugins) { + plugin.apply(compiler); + } + } + compiler.hooks.environment.call(); + compiler.hooks.afterEnvironment.call(); + compiler.options = new WebpackOptionsApply().process(options, compiler); + } else { + throw new Error("Invalid argument: options"); + } + if (callback) { + if (typeof callback !== "function") { + throw new Error("Invalid argument: callback"); + } + if ( + options.watch === true || + (Array.isArray(options) && options.some(o => o.watch)) + ) { + const watchOptions = Array.isArray(options) + ? options.map(o => o.watchOptions || {}) + : options.watchOptions || {}; + return compiler.watch(watchOptions, callback); + } + compiler.run(callback); + } + return compiler; +}; + +exports = module.exports = webpack; +exports.version = version; + +webpack.WebpackOptionsDefaulter = WebpackOptionsDefaulter; +webpack.WebpackOptionsApply = WebpackOptionsApply; +webpack.Compiler = Compiler; +webpack.MultiCompiler = MultiCompiler; +webpack.NodeEnvironmentPlugin = NodeEnvironmentPlugin; +// @ts-ignore Global @this directive is not supported +webpack.validate = validateSchema.bind(this, webpackOptionsSchema); +webpack.validateSchema = validateSchema; +webpack.WebpackOptionsValidationError = WebpackOptionsValidationError; + +const exportPlugins = (obj, mappings) => { + for (const name of Object.keys(mappings)) { + Object.defineProperty(obj, name, { + configurable: false, + enumerable: true, + get: mappings[name] + }); + } +}; + +exportPlugins(exports, { + AutomaticPrefetchPlugin: () => require("./AutomaticPrefetchPlugin"), + BannerPlugin: () => require("./BannerPlugin"), + CachePlugin: () => require("./CachePlugin"), + ContextExclusionPlugin: () => require("./ContextExclusionPlugin"), + ContextReplacementPlugin: () => require("./ContextReplacementPlugin"), + DefinePlugin: () => require("./DefinePlugin"), + Dependency: () => require("./Dependency"), + DllPlugin: () => require("./DllPlugin"), + DllReferencePlugin: () => require("./DllReferencePlugin"), + EnvironmentPlugin: () => require("./EnvironmentPlugin"), + EvalDevToolModulePlugin: () => require("./EvalDevToolModulePlugin"), + EvalSourceMapDevToolPlugin: () => require("./EvalSourceMapDevToolPlugin"), + ExtendedAPIPlugin: () => require("./ExtendedAPIPlugin"), + ExternalsPlugin: () => require("./ExternalsPlugin"), + HashedModuleIdsPlugin: () => require("./HashedModuleIdsPlugin"), + HotModuleReplacementPlugin: () => require("./HotModuleReplacementPlugin"), + IgnorePlugin: () => require("./IgnorePlugin"), + LibraryTemplatePlugin: () => require("./LibraryTemplatePlugin"), + LoaderOptionsPlugin: () => require("./LoaderOptionsPlugin"), + LoaderTargetPlugin: () => require("./LoaderTargetPlugin"), + MemoryOutputFileSystem: () => require("./MemoryOutputFileSystem"), + Module: () => require("./Module"), + ModuleFilenameHelpers: () => require("./ModuleFilenameHelpers"), + NamedChunksPlugin: () => require("./NamedChunksPlugin"), + NamedModulesPlugin: () => require("./NamedModulesPlugin"), + NoEmitOnErrorsPlugin: () => require("./NoEmitOnErrorsPlugin"), + NormalModuleReplacementPlugin: () => + require("./NormalModuleReplacementPlugin"), + PrefetchPlugin: () => require("./PrefetchPlugin"), + ProgressPlugin: () => require("./ProgressPlugin"), + ProvidePlugin: () => require("./ProvidePlugin"), + SetVarMainTemplatePlugin: () => require("./SetVarMainTemplatePlugin"), + SingleEntryPlugin: () => require("./SingleEntryPlugin"), + SourceMapDevToolPlugin: () => require("./SourceMapDevToolPlugin"), + Stats: () => require("./Stats"), + Template: () => require("./Template"), + UmdMainTemplatePlugin: () => require("./UmdMainTemplatePlugin"), + WatchIgnorePlugin: () => require("./WatchIgnorePlugin") +}); +exportPlugins((exports.dependencies = {}), { + DependencyReference: () => require("./dependencies/DependencyReference") +}); +exportPlugins((exports.optimize = {}), { + AggressiveMergingPlugin: () => require("./optimize/AggressiveMergingPlugin"), + AggressiveSplittingPlugin: () => + require("./optimize/AggressiveSplittingPlugin"), + ChunkModuleIdRangePlugin: () => + require("./optimize/ChunkModuleIdRangePlugin"), + LimitChunkCountPlugin: () => require("./optimize/LimitChunkCountPlugin"), + MinChunkSizePlugin: () => require("./optimize/MinChunkSizePlugin"), + ModuleConcatenationPlugin: () => + require("./optimize/ModuleConcatenationPlugin"), + OccurrenceOrderPlugin: () => require("./optimize/OccurrenceOrderPlugin"), + OccurrenceModuleOrderPlugin: () => + require("./optimize/OccurrenceModuleOrderPlugin"), + OccurrenceChunkOrderPlugin: () => + require("./optimize/OccurrenceChunkOrderPlugin"), + RuntimeChunkPlugin: () => require("./optimize/RuntimeChunkPlugin"), + SideEffectsFlagPlugin: () => require("./optimize/SideEffectsFlagPlugin"), + SplitChunksPlugin: () => require("./optimize/SplitChunksPlugin") +}); +exportPlugins((exports.web = {}), { + FetchCompileWasmTemplatePlugin: () => + require("./web/FetchCompileWasmTemplatePlugin"), + JsonpTemplatePlugin: () => require("./web/JsonpTemplatePlugin") +}); +exportPlugins((exports.webworker = {}), { + WebWorkerTemplatePlugin: () => require("./webworker/WebWorkerTemplatePlugin") +}); +exportPlugins((exports.node = {}), { + NodeTemplatePlugin: () => require("./node/NodeTemplatePlugin"), + ReadFileCompileWasmTemplatePlugin: () => + require("./node/ReadFileCompileWasmTemplatePlugin") +}); +exportPlugins((exports.debug = {}), { + ProfilingPlugin: () => require("./debug/ProfilingPlugin") +}); +exportPlugins((exports.util = {}), { + createHash: () => require("./util/createHash") +}); + +const defineMissingPluginError = (namespace, pluginName, errorMessage) => { + Object.defineProperty(namespace, pluginName, { + configurable: false, + enumerable: true, + get() { + throw new RemovedPluginError(errorMessage); + } + }); +}; + +// TODO remove in webpack 5 +defineMissingPluginError( + exports.optimize, + "UglifyJsPlugin", + "webpack.optimize.UglifyJsPlugin has been removed, please use config.optimization.minimize instead." +); + +// TODO remove in webpack 5 +defineMissingPluginError( + exports.optimize, + "CommonsChunkPlugin", + "webpack.optimize.CommonsChunkPlugin has been removed, please use config.optimization.splitChunks instead." +); diff --git a/node_modules/webpack/lib/webpack.web.js b/node_modules/webpack/lib/webpack.web.js index 9747e11e5..1f60eab7f 100644 --- a/node_modules/webpack/lib/webpack.web.js +++ b/node_modules/webpack/lib/webpack.web.js @@ -1,29 +1,31 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const Compiler = require("./Compiler");
-const WebEnvironmentPlugin = require("./web/WebEnvironmentPlugin");
-const WebpackOptionsApply = require("./WebpackOptionsApply");
-const WebpackOptionsDefaulter = require("./WebpackOptionsDefaulter");
-
-function webpack(options, callback) {
- new WebpackOptionsDefaulter().process(options);
-
- const compiler = new Compiler();
- compiler.options = options;
- compiler.options = new WebpackOptionsApply().process(options, compiler);
- new WebEnvironmentPlugin(options.inputFileSystem, options.outputFileSystem).apply(compiler);
- if(callback) {
- compiler.run(callback);
- }
- return compiler;
-}
-module.exports = webpack;
-
-webpack.WebpackOptionsDefaulter = WebpackOptionsDefaulter;
-webpack.WebpackOptionsApply = WebpackOptionsApply;
-webpack.Compiler = Compiler;
-webpack.WebEnvironmentPlugin = WebEnvironmentPlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Compiler = require("./Compiler"); +const WebEnvironmentPlugin = require("./web/WebEnvironmentPlugin"); +const WebpackOptionsApply = require("./WebpackOptionsApply"); +const WebpackOptionsDefaulter = require("./WebpackOptionsDefaulter"); + +const webpack = (options, callback) => { + new WebpackOptionsDefaulter().process(options); + + const compiler = new Compiler(); + compiler.options = new WebpackOptionsApply().process(options, compiler); + new WebEnvironmentPlugin( + options.inputFileSystem, + options.outputFileSystem + ).apply(compiler); + if (callback) { + compiler.run(callback); + } + return compiler; +}; +module.exports = webpack; + +webpack.WebpackOptionsDefaulter = WebpackOptionsDefaulter; +webpack.WebpackOptionsApply = WebpackOptionsApply; +webpack.Compiler = Compiler; +webpack.WebEnvironmentPlugin = WebEnvironmentPlugin; diff --git a/node_modules/webpack/lib/webworker/WebWorkerChunkTemplatePlugin.js b/node_modules/webpack/lib/webworker/WebWorkerChunkTemplatePlugin.js index 3944f3cfc..f44ca26cd 100644 --- a/node_modules/webpack/lib/webworker/WebWorkerChunkTemplatePlugin.js +++ b/node_modules/webpack/lib/webworker/WebWorkerChunkTemplatePlugin.js @@ -1,29 +1,35 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const ConcatSource = require("webpack-sources").ConcatSource;
-const Template = require("../Template");
-
-class WebWorkerChunkTemplatePlugin {
-
- apply(chunkTemplate) {
- chunkTemplate.plugin("render", function(modules, chunk) {
- const chunkCallbackName = this.outputOptions.chunkCallbackName || Template.toIdentifier("webpackChunk" + (this.outputOptions.library || ""));
- const source = new ConcatSource();
- source.add(`${chunkCallbackName}(${JSON.stringify(chunk.ids)},`);
- source.add(modules);
- source.add(")");
- return source;
- });
- chunkTemplate.plugin("hash", function(hash) {
- hash.update("webworker");
- hash.update("3");
- hash.update(`${this.outputOptions.chunkCallbackName}`);
- hash.update(`${this.outputOptions.library}`);
- });
- }
-}
-module.exports = WebWorkerChunkTemplatePlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const { ConcatSource } = require("webpack-sources"); + +class WebWorkerChunkTemplatePlugin { + apply(chunkTemplate) { + chunkTemplate.hooks.render.tap( + "WebWorkerChunkTemplatePlugin", + (modules, chunk) => { + const chunkCallbackName = chunkTemplate.outputOptions.chunkCallbackName; + const globalObject = chunkTemplate.outputOptions.globalObject; + const source = new ConcatSource(); + source.add( + `${globalObject}[${JSON.stringify( + chunkCallbackName + )}](${JSON.stringify(chunk.ids)},` + ); + source.add(modules); + source.add(")"); + return source; + } + ); + chunkTemplate.hooks.hash.tap("WebWorkerChunkTemplatePlugin", hash => { + hash.update("webworker"); + hash.update("3"); + hash.update(`${chunkTemplate.outputOptions.chunkCallbackName}`); + hash.update(`${chunkTemplate.outputOptions.globalObject}`); + }); + } +} +module.exports = WebWorkerChunkTemplatePlugin; diff --git a/node_modules/webpack/lib/webworker/WebWorkerHotUpdateChunkTemplatePlugin.js b/node_modules/webpack/lib/webworker/WebWorkerHotUpdateChunkTemplatePlugin.js index c128be7c7..8b0261194 100644 --- a/node_modules/webpack/lib/webworker/WebWorkerHotUpdateChunkTemplatePlugin.js +++ b/node_modules/webpack/lib/webworker/WebWorkerHotUpdateChunkTemplatePlugin.js @@ -1,28 +1,40 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-const ConcatSource = require("webpack-sources").ConcatSource;
-const Template = require("../Template");
-
-class WebWorkerHotUpdateChunkTemplatePlugin {
-
- apply(hotUpdateChunkTemplate) {
- hotUpdateChunkTemplate.plugin("render", function(modulesSource, modules, removedModules, hash, id) {
- const chunkCallbackName = this.outputOptions.hotUpdateFunction || Template.toIdentifier("webpackHotUpdate" + (this.outputOptions.library || ""));
- const source = new ConcatSource();
- source.add(chunkCallbackName + "(" + JSON.stringify(id) + ",");
- source.add(modulesSource);
- source.add(")");
- return source;
- });
- hotUpdateChunkTemplate.plugin("hash", function(hash) {
- hash.update("WebWorkerHotUpdateChunkTemplatePlugin");
- hash.update("3");
- hash.update(this.outputOptions.hotUpdateFunction + "");
- hash.update(this.outputOptions.library + "");
- });
- }
-}
-module.exports = WebWorkerHotUpdateChunkTemplatePlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; +const { ConcatSource } = require("webpack-sources"); + +class WebWorkerHotUpdateChunkTemplatePlugin { + apply(hotUpdateChunkTemplate) { + hotUpdateChunkTemplate.hooks.render.tap( + "WebWorkerHotUpdateChunkTemplatePlugin", + (modulesSource, modules, removedModules, hash, id) => { + const hotUpdateFunction = + hotUpdateChunkTemplate.outputOptions.hotUpdateFunction; + const globalObject = hotUpdateChunkTemplate.outputOptions.globalObject; + const source = new ConcatSource(); + source.add( + `${globalObject}[${JSON.stringify( + hotUpdateFunction + )}](${JSON.stringify(id)},` + ); + source.add(modulesSource); + source.add(")"); + return source; + } + ); + hotUpdateChunkTemplate.hooks.hash.tap( + "WebWorkerHotUpdateChunkTemplatePlugin", + hash => { + hash.update("WebWorkerHotUpdateChunkTemplatePlugin"); + hash.update("3"); + hash.update( + hotUpdateChunkTemplate.outputOptions.hotUpdateFunction + "" + ); + hash.update(hotUpdateChunkTemplate.outputOptions.globalObject + ""); + } + ); + } +} +module.exports = WebWorkerHotUpdateChunkTemplatePlugin; diff --git a/node_modules/webpack/lib/webworker/WebWorkerMainTemplate.runtime.js b/node_modules/webpack/lib/webworker/WebWorkerMainTemplate.runtime.js index 9b6c59fea..8c63f7729 100644 --- a/node_modules/webpack/lib/webworker/WebWorkerMainTemplate.runtime.js +++ b/node_modules/webpack/lib/webworker/WebWorkerMainTemplate.runtime.js @@ -1,58 +1,65 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-/*globals installedChunks hotAddUpdateChunk parentHotUpdateCallback importScripts XMLHttpRequest $require$ $hotChunkFilename$ $hotMainFilename$ */
-module.exports = function() {
- function webpackHotUpdateCallback(chunkId, moreModules) { // eslint-disable-line no-unused-vars
- hotAddUpdateChunk(chunkId, moreModules);
- if(parentHotUpdateCallback) parentHotUpdateCallback(chunkId, moreModules);
- } //$semicolon
-
- function hotDownloadUpdateChunk(chunkId) { // eslint-disable-line no-unused-vars
- importScripts($require$.p + $hotChunkFilename$);
- }
-
- function hotDownloadManifest(requestTimeout) { // eslint-disable-line no-unused-vars
- requestTimeout = requestTimeout || 10000;
- return new Promise(function(resolve, reject) {
- if(typeof XMLHttpRequest === "undefined")
- return reject(new Error("No browser support"));
- try {
- var request = new XMLHttpRequest();
- var requestPath = $require$.p + $hotMainFilename$;
- request.open("GET", requestPath, true);
- request.timeout = requestTimeout;
- request.send(null);
- } catch(err) {
- return reject(err);
- }
- request.onreadystatechange = function() {
- if(request.readyState !== 4) return;
- if(request.status === 0) {
- // timeout
- reject(new Error("Manifest request to " + requestPath + " timed out."));
- } else if(request.status === 404) {
- // no update available
- resolve();
- } else if(request.status !== 200 && request.status !== 304) {
- // other failure
- reject(new Error("Manifest request to " + requestPath + " failed."));
- } else {
- // success
- try {
- var update = JSON.parse(request.responseText);
- } catch(e) {
- reject(e);
- return;
- }
- resolve(update);
- }
- };
- });
- }
-
- function hotDisposeChunk(chunkId) { //eslint-disable-line no-unused-vars
- delete installedChunks[chunkId];
- }
-};
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +/*globals installedChunks hotAddUpdateChunk parentHotUpdateCallback importScripts XMLHttpRequest $require$ $hotChunkFilename$ $hotMainFilename$ */ +module.exports = function() { + // eslint-disable-next-line no-unused-vars + function webpackHotUpdateCallback(chunkId, moreModules) { + hotAddUpdateChunk(chunkId, moreModules); + if (parentHotUpdateCallback) parentHotUpdateCallback(chunkId, moreModules); + } //$semicolon + + // eslint-disable-next-line no-unused-vars + function hotDownloadUpdateChunk(chunkId) { + importScripts($require$.p + $hotChunkFilename$); + } + + // eslint-disable-next-line no-unused-vars + function hotDownloadManifest(requestTimeout) { + requestTimeout = requestTimeout || 10000; + return new Promise(function(resolve, reject) { + if (typeof XMLHttpRequest === "undefined") { + return reject(new Error("No browser support")); + } + try { + var request = new XMLHttpRequest(); + var requestPath = $require$.p + $hotMainFilename$; + request.open("GET", requestPath, true); + request.timeout = requestTimeout; + request.send(null); + } catch (err) { + return reject(err); + } + request.onreadystatechange = function() { + if (request.readyState !== 4) return; + if (request.status === 0) { + // timeout + reject( + new Error("Manifest request to " + requestPath + " timed out.") + ); + } else if (request.status === 404) { + // no update available + resolve(); + } else if (request.status !== 200 && request.status !== 304) { + // other failure + reject(new Error("Manifest request to " + requestPath + " failed.")); + } else { + // success + try { + var update = JSON.parse(request.responseText); + } catch (e) { + reject(e); + return; + } + resolve(update); + } + }; + }); + } + + //eslint-disable-next-line no-unused-vars + function hotDisposeChunk(chunkId) { + delete installedChunks[chunkId]; + } +}; diff --git a/node_modules/webpack/lib/webworker/WebWorkerMainTemplatePlugin.js b/node_modules/webpack/lib/webworker/WebWorkerMainTemplatePlugin.js index ff2d6c2f5..39f7dabbd 100644 --- a/node_modules/webpack/lib/webworker/WebWorkerMainTemplatePlugin.js +++ b/node_modules/webpack/lib/webworker/WebWorkerMainTemplatePlugin.js @@ -1,105 +1,191 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const Template = require("../Template");
-
-class WebWorkerMainTemplatePlugin {
- apply(mainTemplate) {
- mainTemplate.plugin("local-vars", function(source, chunk) {
- if(chunk.chunks.length > 0) {
- return this.asString([
- source,
- "",
- "// object to store loaded chunks",
- "// \"1\" means \"already loaded\"",
- "var installedChunks = {",
- this.indent(
- chunk.ids.map((id) => `${id}: 1`).join(",\n")
- ),
- "};"
- ]);
- }
- return source;
- });
- mainTemplate.plugin("require-ensure", function(_, chunk, hash) {
- const chunkFilename = this.outputOptions.chunkFilename;
- return this.asString([
- "return new Promise(function(resolve) {",
- this.indent([
- "// \"1\" is the signal for \"already loaded\"",
- "if(!installedChunks[chunkId]) {",
- this.indent([
- "importScripts(" +
- this.applyPluginsWaterfall("asset-path", JSON.stringify(chunkFilename), {
- hash: `" + ${this.renderCurrentHashCode(hash)} + "`,
- hashWithLength: (length) => `" + ${this.renderCurrentHashCode(hash, length)} + "`,
- chunk: {
- id: "\" + chunkId + \""
- }
- }) + ");"
- ]),
- "}",
- "resolve();"
- ]),
- "});"
- ]);
- });
- mainTemplate.plugin("bootstrap", function(source, chunk, hash) {
- if(chunk.chunks.length > 0) {
- const chunkCallbackName = this.outputOptions.chunkCallbackName || Template.toIdentifier("webpackChunk" + (this.outputOptions.library || ""));
- return this.asString([
- source,
- `this[${JSON.stringify(chunkCallbackName)}] = function webpackChunkCallback(chunkIds, moreModules) {`,
- this.indent([
- "for(var moduleId in moreModules) {",
- this.indent(this.renderAddModule(hash, chunk, "moduleId", "moreModules[moduleId]")),
- "}",
- "while(chunkIds.length)",
- this.indent("installedChunks[chunkIds.pop()] = 1;")
- ]),
- "};"
- ]);
- }
- return source;
- });
- mainTemplate.plugin("hot-bootstrap", function(source, chunk, hash) {
- const hotUpdateChunkFilename = this.outputOptions.hotUpdateChunkFilename;
- const hotUpdateMainFilename = this.outputOptions.hotUpdateMainFilename;
- const hotUpdateFunction = this.outputOptions.hotUpdateFunction || Template.toIdentifier("webpackHotUpdate" + (this.outputOptions.library || ""));
- const currentHotUpdateChunkFilename = this.applyPluginsWaterfall("asset-path", JSON.stringify(hotUpdateChunkFilename), {
- hash: `" + ${this.renderCurrentHashCode(hash)} + "`,
- hashWithLength: (length) => `" + ${this.renderCurrentHashCode(hash, length)} + "`,
- chunk: {
- id: "\" + chunkId + \""
- }
- });
- const currentHotUpdateMainFilename = this.applyPluginsWaterfall("asset-path", JSON.stringify(hotUpdateMainFilename), {
- hash: `" + ${this.renderCurrentHashCode(hash)} + "`,
- hashWithLength: (length) => `" + ${this.renderCurrentHashCode(hash, length)} + "`,
- });
-
- return source + "\n" +
- `var parentHotUpdateCallback = self[${JSON.stringify(hotUpdateFunction)}];\n` +
- `self[${JSON.stringify(hotUpdateFunction)}] = ` +
- Template.getFunctionContent(require("./WebWorkerMainTemplate.runtime.js"))
- .replace(/\/\/\$semicolon/g, ";")
- .replace(/\$require\$/g, this.requireFn)
- .replace(/\$hotMainFilename\$/g, currentHotUpdateMainFilename)
- .replace(/\$hotChunkFilename\$/g, currentHotUpdateChunkFilename)
- .replace(/\$hash\$/g, JSON.stringify(hash));
- });
- mainTemplate.plugin("hash", function(hash) {
- hash.update("webworker");
- hash.update("3");
- hash.update(`${this.outputOptions.publicPath}`);
- hash.update(`${this.outputOptions.filename}`);
- hash.update(`${this.outputOptions.chunkFilename}`);
- hash.update(`${this.outputOptions.chunkCallbackName}`);
- hash.update(`${this.outputOptions.library}`);
- });
- }
-}
-module.exports = WebWorkerMainTemplatePlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Template = require("../Template"); + +class WebWorkerMainTemplatePlugin { + apply(mainTemplate) { + const needChunkOnDemandLoadingCode = chunk => { + for (const chunkGroup of chunk.groupsIterable) { + if (chunkGroup.getNumberOfChildren() > 0) return true; + } + return false; + }; + mainTemplate.hooks.localVars.tap( + "WebWorkerMainTemplatePlugin", + (source, chunk) => { + if (needChunkOnDemandLoadingCode(chunk)) { + return Template.asString([ + source, + "", + "// object to store loaded chunks", + '// "1" means "already loaded"', + "var installedChunks = {", + Template.indent( + chunk.ids.map(id => `${JSON.stringify(id)}: 1`).join(",\n") + ), + "};" + ]); + } + return source; + } + ); + mainTemplate.hooks.requireEnsure.tap( + "WebWorkerMainTemplatePlugin", + (_, chunk, hash) => { + const chunkFilename = mainTemplate.outputOptions.chunkFilename; + const chunkMaps = chunk.getChunkMaps(); + return Template.asString([ + "promises.push(Promise.resolve().then(function() {", + Template.indent([ + '// "1" is the signal for "already loaded"', + "if(!installedChunks[chunkId]) {", + Template.indent([ + "importScripts(" + + mainTemplate.getAssetPath(JSON.stringify(chunkFilename), { + hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, + hashWithLength: length => + `" + ${mainTemplate.renderCurrentHashCode( + hash, + length + )} + "`, + chunk: { + id: '" + chunkId + "', + hash: `" + ${JSON.stringify(chunkMaps.hash)}[chunkId] + "`, + hashWithLength(length) { + const shortChunkHashMap = Object.create(null); + for (const chunkId of Object.keys(chunkMaps.hash)) { + if (typeof chunkMaps.hash[chunkId] === "string") { + shortChunkHashMap[chunkId] = chunkMaps.hash[ + chunkId + ].substr(0, length); + } + } + return `" + ${JSON.stringify( + shortChunkHashMap + )}[chunkId] + "`; + }, + contentHash: { + javascript: `" + ${JSON.stringify( + chunkMaps.contentHash.javascript + )}[chunkId] + "` + }, + contentHashWithLength: { + javascript: length => { + const shortContentHashMap = {}; + const contentHash = chunkMaps.contentHash.javascript; + for (const chunkId of Object.keys(contentHash)) { + if (typeof contentHash[chunkId] === "string") { + shortContentHashMap[chunkId] = contentHash[ + chunkId + ].substr(0, length); + } + } + return `" + ${JSON.stringify( + shortContentHashMap + )}[chunkId] + "`; + } + }, + name: `" + (${JSON.stringify( + chunkMaps.name + )}[chunkId]||chunkId) + "` + }, + contentHashType: "javascript" + }) + + ");" + ]), + "}" + ]), + "}));" + ]); + } + ); + mainTemplate.hooks.bootstrap.tap( + "WebWorkerMainTemplatePlugin", + (source, chunk, hash) => { + if (needChunkOnDemandLoadingCode(chunk)) { + const chunkCallbackName = + mainTemplate.outputOptions.chunkCallbackName; + const globalObject = mainTemplate.outputOptions.globalObject; + return Template.asString([ + source, + `${globalObject}[${JSON.stringify( + chunkCallbackName + )}] = function webpackChunkCallback(chunkIds, moreModules) {`, + Template.indent([ + "for(var moduleId in moreModules) {", + Template.indent( + mainTemplate.renderAddModule( + hash, + chunk, + "moduleId", + "moreModules[moduleId]" + ) + ), + "}", + "while(chunkIds.length)", + Template.indent("installedChunks[chunkIds.pop()] = 1;") + ]), + "};" + ]); + } + return source; + } + ); + mainTemplate.hooks.hotBootstrap.tap( + "WebWorkerMainTemplatePlugin", + (source, chunk, hash) => { + const hotUpdateChunkFilename = + mainTemplate.outputOptions.hotUpdateChunkFilename; + const hotUpdateMainFilename = + mainTemplate.outputOptions.hotUpdateMainFilename; + const hotUpdateFunction = mainTemplate.outputOptions.hotUpdateFunction; + const globalObject = mainTemplate.outputOptions.globalObject; + const currentHotUpdateChunkFilename = mainTemplate.getAssetPath( + JSON.stringify(hotUpdateChunkFilename), + { + hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, + hashWithLength: length => + `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`, + chunk: { + id: '" + chunkId + "' + } + } + ); + const currentHotUpdateMainFilename = mainTemplate.getAssetPath( + JSON.stringify(hotUpdateMainFilename), + { + hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, + hashWithLength: length => + `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "` + } + ); + + return ( + source + + "\n" + + `var parentHotUpdateCallback = ${globalObject}[${JSON.stringify( + hotUpdateFunction + )}];\n` + + `${globalObject}[${JSON.stringify(hotUpdateFunction)}] = ` + + Template.getFunctionContent( + require("./WebWorkerMainTemplate.runtime") + ) + .replace(/\/\/\$semicolon/g, ";") + .replace(/\$require\$/g, mainTemplate.requireFn) + .replace(/\$hotMainFilename\$/g, currentHotUpdateMainFilename) + .replace(/\$hotChunkFilename\$/g, currentHotUpdateChunkFilename) + .replace(/\$hash\$/g, JSON.stringify(hash)) + ); + } + ); + mainTemplate.hooks.hash.tap("WebWorkerMainTemplatePlugin", hash => { + hash.update("webworker"); + hash.update("4"); + }); + } +} +module.exports = WebWorkerMainTemplatePlugin; diff --git a/node_modules/webpack/lib/webworker/WebWorkerTemplatePlugin.js b/node_modules/webpack/lib/webworker/WebWorkerTemplatePlugin.js index 64f1e00f5..5ad89f37a 100644 --- a/node_modules/webpack/lib/webworker/WebWorkerTemplatePlugin.js +++ b/node_modules/webpack/lib/webworker/WebWorkerTemplatePlugin.js @@ -1,20 +1,25 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-"use strict";
-
-const WebWorkerMainTemplatePlugin = require("./WebWorkerMainTemplatePlugin");
-const WebWorkerChunkTemplatePlugin = require("./WebWorkerChunkTemplatePlugin");
-const WebWorkerHotUpdateChunkTemplatePlugin = require("./WebWorkerHotUpdateChunkTemplatePlugin");
-
-class WebWorkerTemplatePlugin {
- apply(compiler) {
- compiler.plugin("this-compilation", compilation => {
- compilation.mainTemplate.apply(new WebWorkerMainTemplatePlugin());
- compilation.chunkTemplate.apply(new WebWorkerChunkTemplatePlugin());
- compilation.hotUpdateChunkTemplate.apply(new WebWorkerHotUpdateChunkTemplatePlugin());
- });
- }
-}
-module.exports = WebWorkerTemplatePlugin;
+/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const WebWorkerMainTemplatePlugin = require("./WebWorkerMainTemplatePlugin"); +const WebWorkerChunkTemplatePlugin = require("./WebWorkerChunkTemplatePlugin"); +const WebWorkerHotUpdateChunkTemplatePlugin = require("./WebWorkerHotUpdateChunkTemplatePlugin"); + +class WebWorkerTemplatePlugin { + apply(compiler) { + compiler.hooks.thisCompilation.tap( + "WebWorkerTemplatePlugin", + compilation => { + new WebWorkerMainTemplatePlugin().apply(compilation.mainTemplate); + new WebWorkerChunkTemplatePlugin().apply(compilation.chunkTemplate); + new WebWorkerHotUpdateChunkTemplatePlugin().apply( + compilation.hotUpdateChunkTemplate + ); + } + ); + } +} +module.exports = WebWorkerTemplatePlugin; diff --git a/node_modules/webpack/node_modules/.bin/json5 b/node_modules/webpack/node_modules/.bin/json5 deleted file mode 120000 index 519e49ec8..000000000 --- a/node_modules/webpack/node_modules/.bin/json5 +++ /dev/null @@ -1 +0,0 @@ -../../../json5/lib/cli.js
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/CHANGELOG.md b/node_modules/webpack/node_modules/async/CHANGELOG.md deleted file mode 100644 index de85303dc..000000000 --- a/node_modules/webpack/node_modules/async/CHANGELOG.md +++ /dev/null @@ -1,263 +0,0 @@ -# v2.6.0 -- Added missing aliases for many methods. Previously, you could not (e.g.) `require('async/find')` or use `async.anyLimit`. (#1483) -- Improved `queue` performance. (#1448, #1454) -- Add missing sourcemap (#1452, #1453) -- Various doc updates (#1448, #1471, #1483) - -# v2.5.0 -- Added `concatLimit`, the `Limit` equivalent of [`concat`](https://caolan.github.io/async/docs.html#concat) ([#1426](https://github.com/caolan/async/issues/1426), [#1430](https://github.com/caolan/async/pull/1430)) -- `concat` improvements: it now preserves order, handles falsy values and the `iteratee` callback takes a variable number of arguments ([#1437](https://github.com/caolan/async/issues/1437), [#1436](https://github.com/caolan/async/pull/1436)) -- Fixed an issue in `queue` where there was a size discrepancy between `workersList().length` and `running()` ([#1428](https://github.com/caolan/async/issues/1428), [#1429](https://github.com/caolan/async/pull/1429)) -- Various doc fixes ([#1422](https://github.com/caolan/async/issues/1422), [#1424](https://github.com/caolan/async/pull/1424)) - -# v2.4.1 -- Fixed a bug preventing functions wrapped with `timeout()` from being re-used. ([#1418](https://github.com/caolan/async/issues/1418), [#1419](https://github.com/caolan/async/issues/1419)) - -# v2.4.0 -- Added `tryEach`, for running async functions in parallel, where you only expect one to succeed. ([#1365](https://github.com/caolan/async/issues/1365), [#687](https://github.com/caolan/async/issues/687)) -- Improved performance, most notably in `parallel` and `waterfall` ([#1395](https://github.com/caolan/async/issues/1395)) -- Added `queue.remove()`, for removing items in a `queue` ([#1397](https://github.com/caolan/async/issues/1397), [#1391](https://github.com/caolan/async/issues/1391)) -- Fixed using `eval`, preventing Async from running in pages with Content Security Policy ([#1404](https://github.com/caolan/async/issues/1404), [#1403](https://github.com/caolan/async/issues/1403)) -- Fixed errors thrown in an `asyncify`ed function's callback being caught by the underlying Promise ([#1408](https://github.com/caolan/async/issues/1408)) -- Fixed timing of `queue.empty()` ([#1367](https://github.com/caolan/async/issues/1367)) -- Various doc fixes ([#1314](https://github.com/caolan/async/issues/1314), [#1394](https://github.com/caolan/async/issues/1394), [#1412](https://github.com/caolan/async/issues/1412)) - -# v2.3.0 -- Added support for ES2017 `async` functions. Wherever you can pass a Node-style/CPS function that uses a callback, you can also pass an `async` function. Previously, you had to wrap `async` functions with `asyncify`. The caveat is that it will only work if `async` functions are supported natively in your environment, transpiled implementations can't be detected. ([#1386](https://github.com/caolan/async/issues/1386), [#1390](https://github.com/caolan/async/issues/1390)) -- Small doc fix ([#1392](https://github.com/caolan/async/issues/1392)) - -# v2.2.0 -- Added `groupBy`, and the `Series`/`Limit` equivalents, analogous to [`_.groupBy`](http://lodash.com/docs#groupBy) ([#1364](https://github.com/caolan/async/issues/1364)) -- Fixed `transform` bug when `callback` was not passed ([#1381](https://github.com/caolan/async/issues/1381)) -- Added note about `reflect` to `parallel` docs ([#1385](https://github.com/caolan/async/issues/1385)) - -# v2.1.5 -- Fix `auto` bug when function names collided with Array.prototype ([#1358](https://github.com/caolan/async/issues/1358)) -- Improve some error messages ([#1349](https://github.com/caolan/async/issues/1349)) -- Avoid stack overflow case in queue -- Fixed an issue in `some`, `every` and `find` where processing would continue after the result was determined. -- Cleanup implementations of `some`, `every` and `find` - -# v2.1.3 -- Make bundle size smaller -- Create optimized hotpath for `filter` in array case. - -# v2.1.2 -- Fixed a stackoverflow bug with `detect`, `some`, `every` on large inputs ([#1293](https://github.com/caolan/async/issues/1293)). - -# v2.1.0 - -- `retry` and `retryable` now support an optional `errorFilter` function that determines if the `task` should retry on the error ([#1256](https://github.com/caolan/async/issues/1256), [#1261](https://github.com/caolan/async/issues/1261)) -- Optimized array iteration in `race`, `cargo`, `queue`, and `priorityQueue` ([#1253](https://github.com/caolan/async/issues/1253)) -- Added alias documentation to doc site ([#1251](https://github.com/caolan/async/issues/1251), [#1254](https://github.com/caolan/async/issues/1254)) -- Added [BootStrap scrollspy](http://getbootstrap.com/javascript/#scrollspy) to docs to highlight in the sidebar the current method being viewed ([#1289](https://github.com/caolan/async/issues/1289), [#1300](https://github.com/caolan/async/issues/1300)) -- Various minor doc fixes ([#1263](https://github.com/caolan/async/issues/1263), [#1264](https://github.com/caolan/async/issues/1264), [#1271](https://github.com/caolan/async/issues/1271), [#1278](https://github.com/caolan/async/issues/1278), [#1280](https://github.com/caolan/async/issues/1280), [#1282](https://github.com/caolan/async/issues/1282), [#1302](https://github.com/caolan/async/issues/1302)) - -# v2.0.1 - -- Significantly optimized all iteration based collection methods such as `each`, `map`, `filter`, etc ([#1245](https://github.com/caolan/async/issues/1245), [#1246](https://github.com/caolan/async/issues/1246), [#1247](https://github.com/caolan/async/issues/1247)). - -# v2.0.0 - -Lots of changes here! - -First and foremost, we have a slick new [site for docs](https://caolan.github.io/async/). Special thanks to [**@hargasinski**](https://github.com/hargasinski) for his work converting our old docs to `jsdoc` format and implementing the new website. Also huge ups to [**@ivanseidel**](https://github.com/ivanseidel) for designing our new logo. It was a long process for both of these tasks, but I think these changes turned out extraordinary well. - -The biggest feature is modularization. You can now `require("async/series")` to only require the `series` function. Every Async library function is available this way. You still can `require("async")` to require the entire library, like you could do before. - -We also provide Async as a collection of ES2015 modules. You can now `import {each} from 'async-es'` or `import waterfall from 'async-es/waterfall'`. If you are using only a few Async functions, and are using a ES bundler such as Rollup, this can significantly lower your build size. - -Major thanks to [**@Kikobeats**](github.com/Kikobeats), [**@aearly**](github.com/aearly) and [**@megawac**](github.com/megawac) for doing the majority of the modularization work, as well as [**@jdalton**](github.com/jdalton) and [**@Rich-Harris**](github.com/Rich-Harris) for advisory work on the general modularization strategy. - -Another one of the general themes of the 2.0 release is standardization of what an "async" function is. We are now more strictly following the node-style continuation passing style. That is, an async function is a function that: - -1. Takes a variable number of arguments -2. The last argument is always a callback -3. The callback can accept any number of arguments -4. The first argument passed to the callback will be treated as an error result, if the argument is truthy -5. Any number of result arguments can be passed after the "error" argument -6. The callback is called once and exactly once, either on the same tick or later tick of the JavaScript event loop. - -There were several cases where Async accepted some functions that did not strictly have these properties, most notably `auto`, `every`, `some`, and `filter`. - -Another theme is performance. We have eliminated internal deferrals in all cases where they make sense. For example, in `waterfall` and `auto`, there was a `setImmediate` between each task -- these deferrals have been removed. A `setImmediate` call can add up to 1ms of delay. This might not seem like a lot, but it can add up if you are using many Async functions in the course of processing a HTTP request, for example. Nearly all asynchronous functions that do I/O already have some sort of deferral built in, so the extra deferral is unnecessary. The trade-off of this change is removing our built-in stack-overflow defense. Many synchronous callback calls in series can quickly overflow the JS call stack. If you do have a function that is sometimes synchronous (calling its callback on the same tick), and are running into stack overflows, wrap it with `async.ensureAsync()`. - -Another big performance win has been re-implementing `queue`, `cargo`, and `priorityQueue` with [doubly linked lists](https://en.wikipedia.org/wiki/Doubly_linked_list) instead of arrays. This has lead to queues being an order of [magnitude faster on large sets of tasks](https://github.com/caolan/async/pull/1205). - -## New Features - -- Async is now modularized. Individual functions can be `require()`d from the main package. (`require('async/auto')`) ([#984](https://github.com/caolan/async/issues/984), [#996](https://github.com/caolan/async/issues/996)) -- Async is also available as a collection of ES2015 modules in the new `async-es` package. (`import {forEachSeries} from 'async-es'`) ([#984](https://github.com/caolan/async/issues/984), [#996](https://github.com/caolan/async/issues/996)) -- Added `race`, analogous to `Promise.race()`. It will run an array of async tasks in parallel and will call its callback with the result of the first task to respond. ([#568](https://github.com/caolan/async/issues/568), [#1038](https://github.com/caolan/async/issues/1038)) -- Collection methods now accept ES2015 iterators. Maps, Sets, and anything that implements the iterator spec can now be passed directly to `each`, `map`, `parallel`, etc.. ([#579](https://github.com/caolan/async/issues/579), [#839](https://github.com/caolan/async/issues/839), [#1074](https://github.com/caolan/async/issues/1074)) -- Added `mapValues`, for mapping over the properties of an object and returning an object with the same keys. ([#1157](https://github.com/caolan/async/issues/1157), [#1177](https://github.com/caolan/async/issues/1177)) -- Added `timeout`, a wrapper for an async function that will make the task time-out after the specified time. ([#1007](https://github.com/caolan/async/issues/1007), [#1027](https://github.com/caolan/async/issues/1027)) -- Added `reflect` and `reflectAll`, analagous to [`Promise.reflect()`](http://bluebirdjs.com/docs/api/reflect.html), a wrapper for async tasks that always succeeds, by gathering results and errors into an object. ([#942](https://github.com/caolan/async/issues/942), [#1012](https://github.com/caolan/async/issues/1012), [#1095](https://github.com/caolan/async/issues/1095)) -- `constant` supports dynamic arguments -- it will now always use its last argument as the callback. ([#1016](https://github.com/caolan/async/issues/1016), [#1052](https://github.com/caolan/async/issues/1052)) -- `setImmediate` and `nextTick` now support arguments to partially apply to the deferred function, like the node-native versions do. ([#940](https://github.com/caolan/async/issues/940), [#1053](https://github.com/caolan/async/issues/1053)) -- `auto` now supports resolving cyclic dependencies using [Kahn's algorithm](https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm) ([#1140](https://github.com/caolan/async/issues/1140)). -- Added `autoInject`, a relative of `auto` that automatically spreads a task's dependencies as arguments to the task function. ([#608](https://github.com/caolan/async/issues/608), [#1055](https://github.com/caolan/async/issues/1055), [#1099](https://github.com/caolan/async/issues/1099), [#1100](https://github.com/caolan/async/issues/1100)) -- You can now limit the concurrency of `auto` tasks. ([#635](https://github.com/caolan/async/issues/635), [#637](https://github.com/caolan/async/issues/637)) -- Added `retryable`, a relative of `retry` that wraps an async function, making it retry when called. ([#1058](https://github.com/caolan/async/issues/1058)) -- `retry` now supports specifying a function that determines the next time interval, useful for exponential backoff, logging and other retry strategies. ([#1161](https://github.com/caolan/async/issues/1161)) -- `retry` will now pass all of the arguments the task function was resolved with to the callback ([#1231](https://github.com/caolan/async/issues/1231)). -- Added `q.unsaturated` -- callback called when a `queue`'s number of running workers falls below a threshold. ([#868](https://github.com/caolan/async/issues/868), [#1030](https://github.com/caolan/async/issues/1030), [#1033](https://github.com/caolan/async/issues/1033), [#1034](https://github.com/caolan/async/issues/1034)) -- Added `q.error` -- a callback called whenever a `queue` task calls its callback with an error. ([#1170](https://github.com/caolan/async/issues/1170)) -- `applyEach` and `applyEachSeries` now pass results to the final callback. ([#1088](https://github.com/caolan/async/issues/1088)) - -## Breaking changes - -- Calling a callback more than once is considered an error, and an error will be thrown. This had an explicit breaking change in `waterfall`. If you were relying on this behavior, you should more accurately represent your control flow as an event emitter or stream. ([#814](https://github.com/caolan/async/issues/814), [#815](https://github.com/caolan/async/issues/815), [#1048](https://github.com/caolan/async/issues/1048), [#1050](https://github.com/caolan/async/issues/1050)) -- `auto` task functions now always take the callback as the last argument. If a task has dependencies, the `results` object will be passed as the first argument. To migrate old task functions, wrap them with [`_.flip`](https://lodash.com/docs#flip) ([#1036](https://github.com/caolan/async/issues/1036), [#1042](https://github.com/caolan/async/issues/1042)) -- Internal `setImmediate` calls have been refactored away. This may make existing flows vulnerable to stack overflows if you use many synchronous functions in series. Use `ensureAsync` to work around this. ([#696](https://github.com/caolan/async/issues/696), [#704](https://github.com/caolan/async/issues/704), [#1049](https://github.com/caolan/async/issues/1049), [#1050](https://github.com/caolan/async/issues/1050)) -- `map` used to return an object when iterating over an object. `map` now always returns an array, like in other libraries. The previous object behavior has been split out into `mapValues`. ([#1157](https://github.com/caolan/async/issues/1157), [#1177](https://github.com/caolan/async/issues/1177)) -- `filter`, `reject`, `some`, `every`, and related functions now expect an error as the first callback argument, rather than just a simple boolean. Pass `null` as the first argument, or use `fs.access` instead of `fs.exists`. ([#118](https://github.com/caolan/async/issues/118), [#774](https://github.com/caolan/async/issues/774), [#1028](https://github.com/caolan/async/issues/1028), [#1041](https://github.com/caolan/async/issues/1041)) -- `{METHOD}` and `{METHOD}Series` are now implemented in terms of `{METHOD}Limit`. This is a major internal simplification, and is not expected to cause many problems, but it does subtly affect how functions execute internally. ([#778](https://github.com/caolan/async/issues/778), [#847](https://github.com/caolan/async/issues/847)) -- `retry`'s callback is now optional. Previously, omitting the callback would partially apply the function, meaning it could be passed directly as a task to `series` or `auto`. The partially applied "control-flow" behavior has been separated out into `retryable`. ([#1054](https://github.com/caolan/async/issues/1054), [#1058](https://github.com/caolan/async/issues/1058)) -- The test function for `whilst`, `until`, and `during` used to be passed non-error args from the iteratee function's callback, but this led to weirdness where the first call of the test function would be passed no args. We have made it so the test function is never passed extra arguments, and only the `doWhilst`, `doUntil`, and `doDuring` functions pass iteratee callback arguments to the test function ([#1217](https://github.com/caolan/async/issues/1217), [#1224](https://github.com/caolan/async/issues/1224)) -- The `q.tasks` array has been renamed `q._tasks` and is now implemented as a doubly linked list (DLL). Any code that used to interact with this array will need to be updated to either use the provided helpers or support DLLs ([#1205](https://github.com/caolan/async/issues/1205)). -- The timing of the `q.saturated()` callback in a `queue` has been modified to better reflect when tasks pushed to the queue will start queueing. ([#724](https://github.com/caolan/async/issues/724), [#1078](https://github.com/caolan/async/issues/1078)) -- Removed `iterator` method in favour of [ES2015 iterator protocol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators ) which natively supports arrays ([#1237](https://github.com/caolan/async/issues/1237)) -- Dropped support for Component, Jam, SPM, and Volo ([#1175](https://github.com/caolan/async/issues/1175), #[#176](https://github.com/caolan/async/issues/176)) - -## Bug Fixes - -- Improved handling of no dependency cases in `auto` & `autoInject` ([#1147](https://github.com/caolan/async/issues/1147)). -- Fixed a bug where the callback generated by `asyncify` with `Promises` could resolve twice ([#1197](https://github.com/caolan/async/issues/1197)). -- Fixed several documented optional callbacks not actually being optional ([#1223](https://github.com/caolan/async/issues/1223)). - -## Other - -- Added `someSeries` and `everySeries` for symmetry, as well as a complete set of `any`/`anyLimit`/`anySeries` and `all`/`/allLmit`/`allSeries` aliases. -- Added `find` as an alias for `detect. (as well as `findLimit` and `findSeries`). -- Various doc fixes ([#1005](https://github.com/caolan/async/issues/1005), [#1008](https://github.com/caolan/async/issues/1008), [#1010](https://github.com/caolan/async/issues/1010), [#1015](https://github.com/caolan/async/issues/1015), [#1021](https://github.com/caolan/async/issues/1021), [#1037](https://github.com/caolan/async/issues/1037), [#1039](https://github.com/caolan/async/issues/1039), [#1051](https://github.com/caolan/async/issues/1051), [#1102](https://github.com/caolan/async/issues/1102), [#1107](https://github.com/caolan/async/issues/1107), [#1121](https://github.com/caolan/async/issues/1121), [#1123](https://github.com/caolan/async/issues/1123), [#1129](https://github.com/caolan/async/issues/1129), [#1135](https://github.com/caolan/async/issues/1135), [#1138](https://github.com/caolan/async/issues/1138), [#1141](https://github.com/caolan/async/issues/1141), [#1153](https://github.com/caolan/async/issues/1153), [#1216](https://github.com/caolan/async/issues/1216), [#1217](https://github.com/caolan/async/issues/1217), [#1232](https://github.com/caolan/async/issues/1232), [#1233](https://github.com/caolan/async/issues/1233), [#1236](https://github.com/caolan/async/issues/1236), [#1238](https://github.com/caolan/async/issues/1238)) - -Thank you [**@aearly**](github.com/aearly) and [**@megawac**](github.com/megawac) for taking the lead on version 2 of async. - ------------------------------------------- - -# v1.5.2 -- Allow using `"constructor"` as an argument in `memoize` ([#998](https://github.com/caolan/async/issues/998)) -- Give a better error messsage when `auto` dependency checking fails ([#994](https://github.com/caolan/async/issues/994)) -- Various doc updates ([#936](https://github.com/caolan/async/issues/936), [#956](https://github.com/caolan/async/issues/956), [#979](https://github.com/caolan/async/issues/979), [#1002](https://github.com/caolan/async/issues/1002)) - -# v1.5.1 -- Fix issue with `pause` in `queue` with concurrency enabled ([#946](https://github.com/caolan/async/issues/946)) -- `while` and `until` now pass the final result to callback ([#963](https://github.com/caolan/async/issues/963)) -- `auto` will properly handle concurrency when there is no callback ([#966](https://github.com/caolan/async/issues/966)) -- `auto` will no. properly stop execution when an error occurs ([#988](https://github.com/caolan/async/issues/988), [#993](https://github.com/caolan/async/issues/993)) -- Various doc fixes ([#971](https://github.com/caolan/async/issues/971), [#980](https://github.com/caolan/async/issues/980)) - -# v1.5.0 - -- Added `transform`, analogous to [`_.transform`](http://lodash.com/docs#transform) ([#892](https://github.com/caolan/async/issues/892)) -- `map` now returns an object when an object is passed in, rather than array with non-numeric keys. `map` will begin always returning an array with numeric indexes in the next major release. ([#873](https://github.com/caolan/async/issues/873)) -- `auto` now accepts an optional `concurrency` argument to limit the number o. running tasks ([#637](https://github.com/caolan/async/issues/637)) -- Added `queue#workersList()`, to retrieve the lis. of currently running tasks. ([#891](https://github.com/caolan/async/issues/891)) -- Various code simplifications ([#896](https://github.com/caolan/async/issues/896), [#904](https://github.com/caolan/async/issues/904)) -- Various doc fixes :scroll: ([#890](https://github.com/caolan/async/issues/890), [#894](https://github.com/caolan/async/issues/894), [#903](https://github.com/caolan/async/issues/903), [#905](https://github.com/caolan/async/issues/905), [#912](https://github.com/caolan/async/issues/912)) - -# v1.4.2 - -- Ensure coverage files don't get published on npm ([#879](https://github.com/caolan/async/issues/879)) - -# v1.4.1 - -- Add in overlooked `detectLimit` method ([#866](https://github.com/caolan/async/issues/866)) -- Removed unnecessary files from npm releases ([#861](https://github.com/caolan/async/issues/861)) -- Removed usage of a reserved word to prevent :boom: in older environments ([#870](https://github.com/caolan/async/issues/870)) - -# v1.4.0 - -- `asyncify` now supports promises ([#840](https://github.com/caolan/async/issues/840)) -- Added `Limit` versions of `filter` and `reject` ([#836](https://github.com/caolan/async/issues/836)) -- Add `Limit` versions of `detect`, `some` and `every` ([#828](https://github.com/caolan/async/issues/828), [#829](https://github.com/caolan/async/issues/829)) -- `some`, `every` and `detect` now short circuit early ([#828](https://github.com/caolan/async/issues/828), [#829](https://github.com/caolan/async/issues/829)) -- Improve detection of the global object ([#804](https://github.com/caolan/async/issues/804)), enabling use in WebWorkers -- `whilst` now called with arguments from iterator ([#823](https://github.com/caolan/async/issues/823)) -- `during` now gets called with arguments from iterator ([#824](https://github.com/caolan/async/issues/824)) -- Code simplifications and optimizations aplenty ([diff](https://github.com/caolan/async/compare/v1.3.0...v1.4.0)) - - -# v1.3.0 - -New Features: -- Added `constant` -- Added `asyncify`/`wrapSync` for making sync functions work with callbacks. ([#671](https://github.com/caolan/async/issues/671), [#806](https://github.com/caolan/async/issues/806)) -- Added `during` and `doDuring`, which are like `whilst` with an async truth test. ([#800](https://github.com/caolan/async/issues/800)) -- `retry` now accepts an `interval` parameter to specify a delay between retries. ([#793](https://github.com/caolan/async/issues/793)) -- `async` should work better in Web Workers due to better `root` detection ([#804](https://github.com/caolan/async/issues/804)) -- Callbacks are now optional in `whilst`, `doWhilst`, `until`, and `doUntil` ([#642](https://github.com/caolan/async/issues/642)) -- Various internal updates ([#786](https://github.com/caolan/async/issues/786), [#801](https://github.com/caolan/async/issues/801), [#802](https://github.com/caolan/async/issues/802), [#803](https://github.com/caolan/async/issues/803)) -- Various doc fixes ([#790](https://github.com/caolan/async/issues/790), [#794](https://github.com/caolan/async/issues/794)) - -Bug Fixes: -- `cargo` now exposes the `payload` size, and `cargo.payload` can be changed on the fly after the `cargo` is created. ([#740](https://github.com/caolan/async/issues/740), [#744](https://github.com/caolan/async/issues/744), [#783](https://github.com/caolan/async/issues/783)) - - -# v1.2.1 - -Bug Fix: - -- Small regression with synchronous iterator behavior in `eachSeries` with a 1-element array. Before 1.1.0, `eachSeries`'s callback was called on the same tick, which this patch restores. In 2.0.0, it will be called on the next tick. ([#782](https://github.com/caolan/async/issues/782)) - - -# v1.2.0 - -New Features: - -- Added `timesLimit` ([#743](https://github.com/caolan/async/issues/743)) -- `concurrency` can be changed after initialization in `queue` by setting `q.concurrency`. The new concurrency will be reflected the next time a task is processed. ([#747](https://github.com/caolan/async/issues/747), [#772](https://github.com/caolan/async/issues/772)) - -Bug Fixes: - -- Fixed a regression in `each` and family with empty arrays that have additional properties. ([#775](https://github.com/caolan/async/issues/775), [#777](https://github.com/caolan/async/issues/777)) - - -# v1.1.1 - -Bug Fix: - -- Small regression with synchronous iterator behavior in `eachSeries` with a 1-element array. Before 1.1.0, `eachSeries`'s callback was called on the same tick, which this patch restores. In 2.0.0, it will be called on the next tick. ([#782](https://github.com/caolan/async/issues/782)) - - -# v1.1.0 - -New Features: - -- `cargo` now supports all of the same methods and event callbacks as `queue`. -- Added `ensureAsync` - A wrapper that ensures an async function calls its callback on a later tick. ([#769](https://github.com/caolan/async/issues/769)) -- Optimized `map`, `eachOf`, and `waterfall` families of functions -- Passing a `null` or `undefined` array to `map`, `each`, `parallel` and families will be treated as an empty array ([#667](https://github.com/caolan/async/issues/667)). -- The callback is now optional for the composed results of `compose` and `seq`. ([#618](https://github.com/caolan/async/issues/618)) -- Reduced file size by 4kb, (minified version by 1kb) -- Added code coverage through `nyc` and `coveralls` ([#768](https://github.com/caolan/async/issues/768)) - -Bug Fixes: - -- `forever` will no longer stack overflow with a synchronous iterator ([#622](https://github.com/caolan/async/issues/622)) -- `eachLimit` and other limit functions will stop iterating once an error occurs ([#754](https://github.com/caolan/async/issues/754)) -- Always pass `null` in callbacks when there is no error ([#439](https://github.com/caolan/async/issues/439)) -- Ensure proper conditions when calling `drain()` after pushing an empty data set to a queue ([#668](https://github.com/caolan/async/issues/668)) -- `each` and family will properly handle an empty array ([#578](https://github.com/caolan/async/issues/578)) -- `eachSeries` and family will finish if the underlying array is modified during execution ([#557](https://github.com/caolan/async/issues/557)) -- `queue` will throw if a non-function is passed to `q.push()` ([#593](https://github.com/caolan/async/issues/593)) -- Doc fixes ([#629](https://github.com/caolan/async/issues/629), [#766](https://github.com/caolan/async/issues/766)) - - -# v1.0.0 - -No known breaking changes, we are simply complying with semver from here on out. - -Changes: - -- Start using a changelog! -- Add `forEachOf` for iterating over Objects (or to iterate Arrays with indexes available) ([#168](https://github.com/caolan/async/issues/168) [#704](https://github.com/caolan/async/issues/704) [#321](https://github.com/caolan/async/issues/321)) -- Detect deadlocks in `auto` ([#663](https://github.com/caolan/async/issues/663)) -- Better support for require.js ([#527](https://github.com/caolan/async/issues/527)) -- Throw if queue created with concurrency `0` ([#714](https://github.com/caolan/async/issues/714)) -- Fix unneeded iteration in `queue.resume()` ([#758](https://github.com/caolan/async/issues/758)) -- Guard against timer mocking overriding `setImmediate` ([#609](https://github.com/caolan/async/issues/609) [#611](https://github.com/caolan/async/issues/611)) -- Miscellaneous doc fixes ([#542](https://github.com/caolan/async/issues/542) [#596](https://github.com/caolan/async/issues/596) [#615](https://github.com/caolan/async/issues/615) [#628](https://github.com/caolan/async/issues/628) [#631](https://github.com/caolan/async/issues/631) [#690](https://github.com/caolan/async/issues/690) [#729](https://github.com/caolan/async/issues/729)) -- Use single noop function internally ([#546](https://github.com/caolan/async/issues/546)) -- Optimize internal `_each`, `_map` and `_keys` functions. diff --git a/node_modules/webpack/node_modules/async/LICENSE b/node_modules/webpack/node_modules/async/LICENSE deleted file mode 100644 index d807c05ac..000000000 --- a/node_modules/webpack/node_modules/async/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2010-2017 Caolan McMahon - -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. diff --git a/node_modules/webpack/node_modules/async/README.md b/node_modules/webpack/node_modules/async/README.md deleted file mode 100644 index b48c7dee0..000000000 --- a/node_modules/webpack/node_modules/async/README.md +++ /dev/null @@ -1,50 +0,0 @@ - - -[](https://travis-ci.org/caolan/async) -[](https://www.npmjs.com/package/async) -[](https://coveralls.io/r/caolan/async?branch=master) -[](https://gitter.im/caolan/async?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) -[](https://www.libhive.com/providers/npm/packages/async) -[](https://www.jsdelivr.com/package/npm/async) - - -Async is a utility module which provides straight-forward, powerful functions for working with [asynchronous JavaScript](http://caolan.github.io/async/global.html). Although originally designed for use with [Node.js](https://nodejs.org/) and installable via `npm install --save async`, it can also be used directly in the browser. - -For Documentation, visit <https://caolan.github.io/async/> - -*For Async v1.5.x documentation, go [HERE](https://github.com/caolan/async/blob/v1.5.2/README.md)* - - -```javascript -// for use with Node-style callbacks... -var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; -var configs = {}; - -async.forEachOf(obj, (value, key, callback) => { - fs.readFile(__dirname + value, "utf8", (err, data) => { - if (err) return callback(err); - try { - configs[key] = JSON.parse(data); - } catch (e) { - return callback(e); - } - callback(); - }); -}, err => { - if (err) console.error(err.message); - // configs is now a map of JSON data - doSomethingWith(configs); -}); -``` - -```javascript -// ...or ES2017 async functions -async.mapLimit(urls, 5, async function(url) { - const response = await fetch(url) - return response.body -}, (err, results) => { - if (err) throw err - // results is now an array of the response bodies - console.log(results) -}) -``` diff --git a/node_modules/webpack/node_modules/async/all.js b/node_modules/webpack/node_modules/async/all.js deleted file mode 100644 index d0565b045..000000000 --- a/node_modules/webpack/node_modules/async/all.js +++ /dev/null @@ -1,50 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createTester = require('./internal/createTester'); - -var _createTester2 = _interopRequireDefault(_createTester); - -var _doParallel = require('./internal/doParallel'); - -var _doParallel2 = _interopRequireDefault(_doParallel); - -var _notId = require('./internal/notId'); - -var _notId2 = _interopRequireDefault(_notId); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Returns `true` if every element in `coll` satisfies an async test. If any - * iteratee call returns `false`, the main `callback` is immediately called. - * - * @name every - * @static - * @memberOf module:Collections - * @method - * @alias all - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in parallel. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - * @example - * - * async.every(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // if result is true then every file exists - * }); - */ -exports.default = (0, _doParallel2.default)((0, _createTester2.default)(_notId2.default, _notId2.default)); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/allLimit.js b/node_modules/webpack/node_modules/async/allLimit.js deleted file mode 100644 index a1a759a2b..000000000 --- a/node_modules/webpack/node_modules/async/allLimit.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createTester = require('./internal/createTester'); - -var _createTester2 = _interopRequireDefault(_createTester); - -var _doParallelLimit = require('./internal/doParallelLimit'); - -var _doParallelLimit2 = _interopRequireDefault(_doParallelLimit); - -var _notId = require('./internal/notId'); - -var _notId2 = _interopRequireDefault(_notId); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. - * - * @name everyLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.every]{@link module:Collections.every} - * @alias allLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in parallel. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - */ -exports.default = (0, _doParallelLimit2.default)((0, _createTester2.default)(_notId2.default, _notId2.default)); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/allSeries.js b/node_modules/webpack/node_modules/async/allSeries.js deleted file mode 100644 index 23bfebb59..000000000 --- a/node_modules/webpack/node_modules/async/allSeries.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _everyLimit = require('./everyLimit'); - -var _everyLimit2 = _interopRequireDefault(_everyLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. - * - * @name everySeries - * @static - * @memberOf module:Collections - * @method - * @see [async.every]{@link module:Collections.every} - * @alias allSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in series. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - */ -exports.default = (0, _doLimit2.default)(_everyLimit2.default, 1); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/any.js b/node_modules/webpack/node_modules/async/any.js deleted file mode 100644 index a8e70f714..000000000 --- a/node_modules/webpack/node_modules/async/any.js +++ /dev/null @@ -1,52 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createTester = require('./internal/createTester'); - -var _createTester2 = _interopRequireDefault(_createTester); - -var _doParallel = require('./internal/doParallel'); - -var _doParallel2 = _interopRequireDefault(_doParallel); - -var _identity = require('lodash/identity'); - -var _identity2 = _interopRequireDefault(_identity); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Returns `true` if at least one element in the `coll` satisfies an async test. - * If any iteratee call returns `true`, the main `callback` is immediately - * called. - * - * @name some - * @static - * @memberOf module:Collections - * @method - * @alias any - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in parallel. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - * @example - * - * async.some(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // if result is true then at least one of the files exists - * }); - */ -exports.default = (0, _doParallel2.default)((0, _createTester2.default)(Boolean, _identity2.default)); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/anyLimit.js b/node_modules/webpack/node_modules/async/anyLimit.js deleted file mode 100644 index 24ca3f491..000000000 --- a/node_modules/webpack/node_modules/async/anyLimit.js +++ /dev/null @@ -1,43 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createTester = require('./internal/createTester'); - -var _createTester2 = _interopRequireDefault(_createTester); - -var _doParallelLimit = require('./internal/doParallelLimit'); - -var _doParallelLimit2 = _interopRequireDefault(_doParallelLimit); - -var _identity = require('lodash/identity'); - -var _identity2 = _interopRequireDefault(_identity); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. - * - * @name someLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.some]{@link module:Collections.some} - * @alias anyLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in parallel. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - */ -exports.default = (0, _doParallelLimit2.default)((0, _createTester2.default)(Boolean, _identity2.default)); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/anySeries.js b/node_modules/webpack/node_modules/async/anySeries.js deleted file mode 100644 index dc24ed254..000000000 --- a/node_modules/webpack/node_modules/async/anySeries.js +++ /dev/null @@ -1,38 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _someLimit = require('./someLimit'); - -var _someLimit2 = _interopRequireDefault(_someLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. - * - * @name someSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.some]{@link module:Collections.some} - * @alias anySeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in series. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - */ -exports.default = (0, _doLimit2.default)(_someLimit2.default, 1); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/apply.js b/node_modules/webpack/node_modules/async/apply.js deleted file mode 100644 index f590fa574..000000000 --- a/node_modules/webpack/node_modules/async/apply.js +++ /dev/null @@ -1,68 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -exports.default = function (fn /*, ...args*/) { - var args = (0, _slice2.default)(arguments, 1); - return function () /*callArgs*/{ - var callArgs = (0, _slice2.default)(arguments); - return fn.apply(null, args.concat(callArgs)); - }; -}; - -var _slice = require('./internal/slice'); - -var _slice2 = _interopRequireDefault(_slice); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -; - -/** - * Creates a continuation function with some arguments already applied. - * - * Useful as a shorthand when combined with other control flow functions. Any - * arguments passed to the returned function are added to the arguments - * originally passed to apply. - * - * @name apply - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {Function} fn - The function you want to eventually apply all - * arguments to. Invokes with (arguments...). - * @param {...*} arguments... - Any number of arguments to automatically apply - * when the continuation is called. - * @returns {Function} the partially-applied function - * @example - * - * // using apply - * async.parallel([ - * async.apply(fs.writeFile, 'testfile1', 'test1'), - * async.apply(fs.writeFile, 'testfile2', 'test2') - * ]); - * - * - * // the same process without using apply - * async.parallel([ - * function(callback) { - * fs.writeFile('testfile1', 'test1', callback); - * }, - * function(callback) { - * fs.writeFile('testfile2', 'test2', callback); - * } - * ]); - * - * // It's possible to pass any number of additional arguments when calling the - * // continuation: - * - * node> var fn = async.apply(sys.puts, 'one'); - * node> fn('two', 'three'); - * one - * two - * three - */ -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/applyEach.js b/node_modules/webpack/node_modules/async/applyEach.js deleted file mode 100644 index 06c08450a..000000000 --- a/node_modules/webpack/node_modules/async/applyEach.js +++ /dev/null @@ -1,51 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _applyEach = require('./internal/applyEach'); - -var _applyEach2 = _interopRequireDefault(_applyEach); - -var _map = require('./map'); - -var _map2 = _interopRequireDefault(_map); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Applies the provided arguments to each function in the array, calling - * `callback` after all functions have completed. If you only provide the first - * argument, `fns`, then it will return a function which lets you pass in the - * arguments as if it were a single function call. If more arguments are - * provided, `callback` is required while `args` is still optional. - * - * @name applyEach - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|Object} fns - A collection of {@link AsyncFunction}s - * to all call with the same arguments - * @param {...*} [args] - any number of separate arguments to pass to the - * function. - * @param {Function} [callback] - the final argument should be the callback, - * called when all functions have completed processing. - * @returns {Function} - If only the first argument, `fns`, is provided, it will - * return a function which lets you pass in the arguments as if it were a single - * function call. The signature is `(..args, callback)`. If invoked with any - * arguments, `callback` is required. - * @example - * - * async.applyEach([enableSearch, updateSchema], 'bucket', callback); - * - * // partial application example: - * async.each( - * buckets, - * async.applyEach([enableSearch, updateSchema]), - * callback - * ); - */ -exports.default = (0, _applyEach2.default)(_map2.default); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/applyEachSeries.js b/node_modules/webpack/node_modules/async/applyEachSeries.js deleted file mode 100644 index ad80280cc..000000000 --- a/node_modules/webpack/node_modules/async/applyEachSeries.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _applyEach = require('./internal/applyEach'); - -var _applyEach2 = _interopRequireDefault(_applyEach); - -var _mapSeries = require('./mapSeries'); - -var _mapSeries2 = _interopRequireDefault(_mapSeries); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time. - * - * @name applyEachSeries - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.applyEach]{@link module:ControlFlow.applyEach} - * @category Control Flow - * @param {Array|Iterable|Object} fns - A collection of {@link AsyncFunction}s to all - * call with the same arguments - * @param {...*} [args] - any number of separate arguments to pass to the - * function. - * @param {Function} [callback] - the final argument should be the callback, - * called when all functions have completed processing. - * @returns {Function} - If only the first argument is provided, it will return - * a function which lets you pass in the arguments as if it were a single - * function call. - */ -exports.default = (0, _applyEach2.default)(_mapSeries2.default); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/asyncify.js b/node_modules/webpack/node_modules/async/asyncify.js deleted file mode 100644 index 5e3fc9155..000000000 --- a/node_modules/webpack/node_modules/async/asyncify.js +++ /dev/null @@ -1,110 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = asyncify; - -var _isObject = require('lodash/isObject'); - -var _isObject2 = _interopRequireDefault(_isObject); - -var _initialParams = require('./internal/initialParams'); - -var _initialParams2 = _interopRequireDefault(_initialParams); - -var _setImmediate = require('./internal/setImmediate'); - -var _setImmediate2 = _interopRequireDefault(_setImmediate); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Take a sync function and make it async, passing its return value to a - * callback. This is useful for plugging sync functions into a waterfall, - * series, or other async functions. Any arguments passed to the generated - * function will be passed to the wrapped function (except for the final - * callback argument). Errors thrown will be passed to the callback. - * - * If the function passed to `asyncify` returns a Promise, that promises's - * resolved/rejected state will be used to call the callback, rather than simply - * the synchronous return value. - * - * This also means you can asyncify ES2017 `async` functions. - * - * @name asyncify - * @static - * @memberOf module:Utils - * @method - * @alias wrapSync - * @category Util - * @param {Function} func - The synchronous function, or Promise-returning - * function to convert to an {@link AsyncFunction}. - * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be - * invoked with `(args..., callback)`. - * @example - * - * // passing a regular synchronous function - * async.waterfall([ - * async.apply(fs.readFile, filename, "utf8"), - * async.asyncify(JSON.parse), - * function (data, next) { - * // data is the result of parsing the text. - * // If there was a parsing error, it would have been caught. - * } - * ], callback); - * - * // passing a function returning a promise - * async.waterfall([ - * async.apply(fs.readFile, filename, "utf8"), - * async.asyncify(function (contents) { - * return db.model.create(contents); - * }), - * function (model, next) { - * // `model` is the instantiated model object. - * // If there was an error, this function would be skipped. - * } - * ], callback); - * - * // es2017 example, though `asyncify` is not needed if your JS environment - * // supports async functions out of the box - * var q = async.queue(async.asyncify(async function(file) { - * var intermediateStep = await processFile(file); - * return await somePromise(intermediateStep) - * })); - * - * q.push(files); - */ -function asyncify(func) { - return (0, _initialParams2.default)(function (args, callback) { - var result; - try { - result = func.apply(this, args); - } catch (e) { - return callback(e); - } - // if result is Promise object - if ((0, _isObject2.default)(result) && typeof result.then === 'function') { - result.then(function (value) { - invokeCallback(callback, null, value); - }, function (err) { - invokeCallback(callback, err.message ? err : new Error(err)); - }); - } else { - callback(null, result); - } - }); -} - -function invokeCallback(callback, error, value) { - try { - callback(error, value); - } catch (e) { - (0, _setImmediate2.default)(rethrow, e); - } -} - -function rethrow(error) { - throw error; -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/auto.js b/node_modules/webpack/node_modules/async/auto.js deleted file mode 100644 index 26c1d562c..000000000 --- a/node_modules/webpack/node_modules/async/auto.js +++ /dev/null @@ -1,289 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -exports.default = function (tasks, concurrency, callback) { - if (typeof concurrency === 'function') { - // concurrency is optional, shift the args. - callback = concurrency; - concurrency = null; - } - callback = (0, _once2.default)(callback || _noop2.default); - var keys = (0, _keys2.default)(tasks); - var numTasks = keys.length; - if (!numTasks) { - return callback(null); - } - if (!concurrency) { - concurrency = numTasks; - } - - var results = {}; - var runningTasks = 0; - var hasError = false; - - var listeners = Object.create(null); - - var readyTasks = []; - - // for cycle detection: - var readyToCheck = []; // tasks that have been identified as reachable - // without the possibility of returning to an ancestor task - var uncheckedDependencies = {}; - - (0, _baseForOwn2.default)(tasks, function (task, key) { - if (!(0, _isArray2.default)(task)) { - // no dependencies - enqueueTask(key, [task]); - readyToCheck.push(key); - return; - } - - var dependencies = task.slice(0, task.length - 1); - var remainingDependencies = dependencies.length; - if (remainingDependencies === 0) { - enqueueTask(key, task); - readyToCheck.push(key); - return; - } - uncheckedDependencies[key] = remainingDependencies; - - (0, _arrayEach2.default)(dependencies, function (dependencyName) { - if (!tasks[dependencyName]) { - throw new Error('async.auto task `' + key + '` has a non-existent dependency `' + dependencyName + '` in ' + dependencies.join(', ')); - } - addListener(dependencyName, function () { - remainingDependencies--; - if (remainingDependencies === 0) { - enqueueTask(key, task); - } - }); - }); - }); - - checkForDeadlocks(); - processQueue(); - - function enqueueTask(key, task) { - readyTasks.push(function () { - runTask(key, task); - }); - } - - function processQueue() { - if (readyTasks.length === 0 && runningTasks === 0) { - return callback(null, results); - } - while (readyTasks.length && runningTasks < concurrency) { - var run = readyTasks.shift(); - run(); - } - } - - function addListener(taskName, fn) { - var taskListeners = listeners[taskName]; - if (!taskListeners) { - taskListeners = listeners[taskName] = []; - } - - taskListeners.push(fn); - } - - function taskComplete(taskName) { - var taskListeners = listeners[taskName] || []; - (0, _arrayEach2.default)(taskListeners, function (fn) { - fn(); - }); - processQueue(); - } - - function runTask(key, task) { - if (hasError) return; - - var taskCallback = (0, _onlyOnce2.default)(function (err, result) { - runningTasks--; - if (arguments.length > 2) { - result = (0, _slice2.default)(arguments, 1); - } - if (err) { - var safeResults = {}; - (0, _baseForOwn2.default)(results, function (val, rkey) { - safeResults[rkey] = val; - }); - safeResults[key] = result; - hasError = true; - listeners = Object.create(null); - - callback(err, safeResults); - } else { - results[key] = result; - taskComplete(key); - } - }); - - runningTasks++; - var taskFn = (0, _wrapAsync2.default)(task[task.length - 1]); - if (task.length > 1) { - taskFn(results, taskCallback); - } else { - taskFn(taskCallback); - } - } - - function checkForDeadlocks() { - // Kahn's algorithm - // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm - // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html - var currentTask; - var counter = 0; - while (readyToCheck.length) { - currentTask = readyToCheck.pop(); - counter++; - (0, _arrayEach2.default)(getDependents(currentTask), function (dependent) { - if (--uncheckedDependencies[dependent] === 0) { - readyToCheck.push(dependent); - } - }); - } - - if (counter !== numTasks) { - throw new Error('async.auto cannot execute tasks due to a recursive dependency'); - } - } - - function getDependents(taskName) { - var result = []; - (0, _baseForOwn2.default)(tasks, function (task, key) { - if ((0, _isArray2.default)(task) && (0, _baseIndexOf2.default)(task, taskName, 0) >= 0) { - result.push(key); - } - }); - return result; - } -}; - -var _arrayEach = require('lodash/_arrayEach'); - -var _arrayEach2 = _interopRequireDefault(_arrayEach); - -var _baseForOwn = require('lodash/_baseForOwn'); - -var _baseForOwn2 = _interopRequireDefault(_baseForOwn); - -var _baseIndexOf = require('lodash/_baseIndexOf'); - -var _baseIndexOf2 = _interopRequireDefault(_baseIndexOf); - -var _isArray = require('lodash/isArray'); - -var _isArray2 = _interopRequireDefault(_isArray); - -var _keys = require('lodash/keys'); - -var _keys2 = _interopRequireDefault(_keys); - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _slice = require('./internal/slice'); - -var _slice2 = _interopRequireDefault(_slice); - -var _once = require('./internal/once'); - -var _once2 = _interopRequireDefault(_once); - -var _onlyOnce = require('./internal/onlyOnce'); - -var _onlyOnce2 = _interopRequireDefault(_onlyOnce); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -module.exports = exports['default']; - -/** - * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on - * their requirements. Each function can optionally depend on other functions - * being completed first, and each function is run as soon as its requirements - * are satisfied. - * - * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence - * will stop. Further tasks will not execute (so any other functions depending - * on it will not run), and the main `callback` is immediately called with the - * error. - * - * {@link AsyncFunction}s also receive an object containing the results of functions which - * have completed so far as the first argument, if they have dependencies. If a - * task function has no dependencies, it will only be passed a callback. - * - * @name auto - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Object} tasks - An object. Each of its properties is either a - * function or an array of requirements, with the {@link AsyncFunction} itself the last item - * in the array. The object's key of a property serves as the name of the task - * defined by that property, i.e. can be used when specifying requirements for - * other tasks. The function receives one or two arguments: - * * a `results` object, containing the results of the previously executed - * functions, only passed if the task has any dependencies, - * * a `callback(err, result)` function, which must be called when finished, - * passing an `error` (which can be `null`) and the result of the function's - * execution. - * @param {number} [concurrency=Infinity] - An optional `integer` for - * determining the maximum number of tasks that can be run in parallel. By - * default, as many as possible. - * @param {Function} [callback] - An optional callback which is called when all - * the tasks have been completed. It receives the `err` argument if any `tasks` - * pass an error to their callback. Results are always returned; however, if an - * error occurs, no further `tasks` will be performed, and the results object - * will only contain partial results. Invoked with (err, results). - * @returns undefined - * @example - * - * async.auto({ - * // this function will just be passed a callback - * readData: async.apply(fs.readFile, 'data.txt', 'utf-8'), - * showData: ['readData', function(results, cb) { - * // results.readData is the file's contents - * // ... - * }] - * }, callback); - * - * async.auto({ - * get_data: function(callback) { - * console.log('in get_data'); - * // async code to get some data - * callback(null, 'data', 'converted to array'); - * }, - * make_folder: function(callback) { - * console.log('in make_folder'); - * // async code to create a directory to store a file in - * // this is run at the same time as getting the data - * callback(null, 'folder'); - * }, - * write_file: ['get_data', 'make_folder', function(results, callback) { - * console.log('in write_file', JSON.stringify(results)); - * // once there is some data and the directory exists, - * // write the data to a file in the directory - * callback(null, 'filename'); - * }], - * email_link: ['write_file', function(results, callback) { - * console.log('in email_link', JSON.stringify(results)); - * // once the file is written let's email a link to it... - * // results.write_file contains the filename returned by write_file. - * callback(null, {'file':results.write_file, 'email':'user@example.com'}); - * }] - * }, function(err, results) { - * console.log('err = ', err); - * console.log('results = ', results); - * }); - */
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/autoInject.js b/node_modules/webpack/node_modules/async/autoInject.js deleted file mode 100644 index bfbe7e8ec..000000000 --- a/node_modules/webpack/node_modules/async/autoInject.js +++ /dev/null @@ -1,170 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = autoInject; - -var _auto = require('./auto'); - -var _auto2 = _interopRequireDefault(_auto); - -var _baseForOwn = require('lodash/_baseForOwn'); - -var _baseForOwn2 = _interopRequireDefault(_baseForOwn); - -var _arrayMap = require('lodash/_arrayMap'); - -var _arrayMap2 = _interopRequireDefault(_arrayMap); - -var _isArray = require('lodash/isArray'); - -var _isArray2 = _interopRequireDefault(_isArray); - -var _trim = require('lodash/trim'); - -var _trim2 = _interopRequireDefault(_trim); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var FN_ARGS = /^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m; -var FN_ARG_SPLIT = /,/; -var FN_ARG = /(=.+)?(\s*)$/; -var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; - -function parseParams(func) { - func = func.toString().replace(STRIP_COMMENTS, ''); - func = func.match(FN_ARGS)[2].replace(' ', ''); - func = func ? func.split(FN_ARG_SPLIT) : []; - func = func.map(function (arg) { - return (0, _trim2.default)(arg.replace(FN_ARG, '')); - }); - return func; -} - -/** - * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent - * tasks are specified as parameters to the function, after the usual callback - * parameter, with the parameter names matching the names of the tasks it - * depends on. This can provide even more readable task graphs which can be - * easier to maintain. - * - * If a final callback is specified, the task results are similarly injected, - * specified as named parameters after the initial error parameter. - * - * The autoInject function is purely syntactic sugar and its semantics are - * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}. - * - * @name autoInject - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.auto]{@link module:ControlFlow.auto} - * @category Control Flow - * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of - * the form 'func([dependencies...], callback). The object's key of a property - * serves as the name of the task defined by that property, i.e. can be used - * when specifying requirements for other tasks. - * * The `callback` parameter is a `callback(err, result)` which must be called - * when finished, passing an `error` (which can be `null`) and the result of - * the function's execution. The remaining parameters name other tasks on - * which the task is dependent, and the results from those tasks are the - * arguments of those parameters. - * @param {Function} [callback] - An optional callback which is called when all - * the tasks have been completed. It receives the `err` argument if any `tasks` - * pass an error to their callback, and a `results` object with any completed - * task results, similar to `auto`. - * @example - * - * // The example from `auto` can be rewritten as follows: - * async.autoInject({ - * get_data: function(callback) { - * // async code to get some data - * callback(null, 'data', 'converted to array'); - * }, - * make_folder: function(callback) { - * // async code to create a directory to store a file in - * // this is run at the same time as getting the data - * callback(null, 'folder'); - * }, - * write_file: function(get_data, make_folder, callback) { - * // once there is some data and the directory exists, - * // write the data to a file in the directory - * callback(null, 'filename'); - * }, - * email_link: function(write_file, callback) { - * // once the file is written let's email a link to it... - * // write_file contains the filename returned by write_file. - * callback(null, {'file':write_file, 'email':'user@example.com'}); - * } - * }, function(err, results) { - * console.log('err = ', err); - * console.log('email_link = ', results.email_link); - * }); - * - * // If you are using a JS minifier that mangles parameter names, `autoInject` - * // will not work with plain functions, since the parameter names will be - * // collapsed to a single letter identifier. To work around this, you can - * // explicitly specify the names of the parameters your task function needs - * // in an array, similar to Angular.js dependency injection. - * - * // This still has an advantage over plain `auto`, since the results a task - * // depends on are still spread into arguments. - * async.autoInject({ - * //... - * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) { - * callback(null, 'filename'); - * }], - * email_link: ['write_file', function(write_file, callback) { - * callback(null, {'file':write_file, 'email':'user@example.com'}); - * }] - * //... - * }, function(err, results) { - * console.log('err = ', err); - * console.log('email_link = ', results.email_link); - * }); - */ -function autoInject(tasks, callback) { - var newTasks = {}; - - (0, _baseForOwn2.default)(tasks, function (taskFn, key) { - var params; - var fnIsAsync = (0, _wrapAsync.isAsync)(taskFn); - var hasNoDeps = !fnIsAsync && taskFn.length === 1 || fnIsAsync && taskFn.length === 0; - - if ((0, _isArray2.default)(taskFn)) { - params = taskFn.slice(0, -1); - taskFn = taskFn[taskFn.length - 1]; - - newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn); - } else if (hasNoDeps) { - // no dependencies, use the function as-is - newTasks[key] = taskFn; - } else { - params = parseParams(taskFn); - if (taskFn.length === 0 && !fnIsAsync && params.length === 0) { - throw new Error("autoInject task functions require explicit parameters."); - } - - // remove callback param - if (!fnIsAsync) params.pop(); - - newTasks[key] = params.concat(newTask); - } - - function newTask(results, taskCb) { - var newArgs = (0, _arrayMap2.default)(params, function (name) { - return results[name]; - }); - newArgs.push(taskCb); - (0, _wrapAsync2.default)(taskFn).apply(null, newArgs); - } - }); - - (0, _auto2.default)(newTasks, callback); -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/bower.json b/node_modules/webpack/node_modules/async/bower.json deleted file mode 100644 index 7dbeb1497..000000000 --- a/node_modules/webpack/node_modules/async/bower.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "name": "async", - "main": "dist/async.js", - "ignore": [ - "bower_components", - "lib", - "mocha_test", - "node_modules", - "perf", - "support", - "**/.*", - "*.config.js", - "*.json", - "index.js", - "Makefile" - ] -} diff --git a/node_modules/webpack/node_modules/async/cargo.js b/node_modules/webpack/node_modules/async/cargo.js deleted file mode 100644 index c7e59c7c5..000000000 --- a/node_modules/webpack/node_modules/async/cargo.js +++ /dev/null @@ -1,94 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = cargo; - -var _queue = require('./internal/queue'); - -var _queue2 = _interopRequireDefault(_queue); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * A cargo of tasks for the worker function to complete. Cargo inherits all of - * the same methods and event callbacks as [`queue`]{@link module:ControlFlow.queue}. - * @typedef {Object} CargoObject - * @memberOf module:ControlFlow - * @property {Function} length - A function returning the number of items - * waiting to be processed. Invoke like `cargo.length()`. - * @property {number} payload - An `integer` for determining how many tasks - * should be process per round. This property can be changed after a `cargo` is - * created to alter the payload on-the-fly. - * @property {Function} push - Adds `task` to the `queue`. The callback is - * called once the `worker` has finished processing the task. Instead of a - * single task, an array of `tasks` can be submitted. The respective callback is - * used for every task in the list. Invoke like `cargo.push(task, [callback])`. - * @property {Function} saturated - A callback that is called when the - * `queue.length()` hits the concurrency and further tasks will be queued. - * @property {Function} empty - A callback that is called when the last item - * from the `queue` is given to a `worker`. - * @property {Function} drain - A callback that is called when the last item - * from the `queue` has returned from the `worker`. - * @property {Function} idle - a function returning false if there are items - * waiting or being processed, or true if not. Invoke like `cargo.idle()`. - * @property {Function} pause - a function that pauses the processing of tasks - * until `resume()` is called. Invoke like `cargo.pause()`. - * @property {Function} resume - a function that resumes the processing of - * queued tasks when the queue is paused. Invoke like `cargo.resume()`. - * @property {Function} kill - a function that removes the `drain` callback and - * empties remaining tasks from the queue forcing it to go idle. Invoke like `cargo.kill()`. - */ - -/** - * Creates a `cargo` object with the specified payload. Tasks added to the - * cargo will be processed altogether (up to the `payload` limit). If the - * `worker` is in progress, the task is queued until it becomes available. Once - * the `worker` has completed some tasks, each callback of those tasks is - * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) - * for how `cargo` and `queue` work. - * - * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers - * at a time, cargo passes an array of tasks to a single worker, repeating - * when the worker is finished. - * - * @name cargo - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.queue]{@link module:ControlFlow.queue} - * @category Control Flow - * @param {AsyncFunction} worker - An asynchronous function for processing an array - * of queued tasks. Invoked with `(tasks, callback)`. - * @param {number} [payload=Infinity] - An optional `integer` for determining - * how many tasks should be processed per round; if omitted, the default is - * unlimited. - * @returns {module:ControlFlow.CargoObject} A cargo object to manage the tasks. Callbacks can - * attached as certain properties to listen for specific events during the - * lifecycle of the cargo and inner queue. - * @example - * - * // create a cargo object with payload 2 - * var cargo = async.cargo(function(tasks, callback) { - * for (var i=0; i<tasks.length; i++) { - * console.log('hello ' + tasks[i].name); - * } - * callback(); - * }, 2); - * - * // add some items - * cargo.push({name: 'foo'}, function(err) { - * console.log('finished processing foo'); - * }); - * cargo.push({name: 'bar'}, function(err) { - * console.log('finished processing bar'); - * }); - * cargo.push({name: 'baz'}, function(err) { - * console.log('finished processing baz'); - * }); - */ -function cargo(worker, payload) { - return (0, _queue2.default)(worker, 1, payload); -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/compose.js b/node_modules/webpack/node_modules/async/compose.js deleted file mode 100644 index 47c49f62d..000000000 --- a/node_modules/webpack/node_modules/async/compose.js +++ /dev/null @@ -1,58 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -exports.default = function () /*...args*/{ - return _seq2.default.apply(null, (0, _slice2.default)(arguments).reverse()); -}; - -var _seq = require('./seq'); - -var _seq2 = _interopRequireDefault(_seq); - -var _slice = require('./internal/slice'); - -var _slice2 = _interopRequireDefault(_slice); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -; - -/** - * Creates a function which is a composition of the passed asynchronous - * functions. Each function consumes the return value of the function that - * follows. Composing functions `f()`, `g()`, and `h()` would produce the result - * of `f(g(h()))`, only this version uses callbacks to obtain the return values. - * - * Each function is executed with the `this` binding of the composed function. - * - * @name compose - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {...AsyncFunction} functions - the asynchronous functions to compose - * @returns {Function} an asynchronous function that is the composed - * asynchronous `functions` - * @example - * - * function add1(n, callback) { - * setTimeout(function () { - * callback(null, n + 1); - * }, 10); - * } - * - * function mul3(n, callback) { - * setTimeout(function () { - * callback(null, n * 3); - * }, 10); - * } - * - * var add1mul3 = async.compose(mul3, add1); - * add1mul3(4, function (err, result) { - * // result now equals 15 - * }); - */ -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/concat.js b/node_modules/webpack/node_modules/async/concat.js deleted file mode 100644 index c39ea0001..000000000 --- a/node_modules/webpack/node_modules/async/concat.js +++ /dev/null @@ -1,43 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -var _concatLimit = require('./concatLimit'); - -var _concatLimit2 = _interopRequireDefault(_concatLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Applies `iteratee` to each item in `coll`, concatenating the results. Returns - * the concatenated list. The `iteratee`s are called in parallel, and the - * results are concatenated as they return. There is no guarantee that the - * results array will be returned in the original order of `coll` passed to the - * `iteratee` function. - * - * @name concat - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, - * which should use an array as its result. Invoked with (item, callback). - * @param {Function} [callback(err)] - A callback which is called after all the - * `iteratee` functions have finished, or an error occurs. Results is an array - * containing the concatenated results of the `iteratee` function. Invoked with - * (err, results). - * @example - * - * async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files) { - * // files is now a list of filenames that exist in the 3 directories - * }); - */ -exports.default = (0, _doLimit2.default)(_concatLimit2.default, Infinity); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/concatLimit.js b/node_modules/webpack/node_modules/async/concatLimit.js deleted file mode 100644 index f32cd4d34..000000000 --- a/node_modules/webpack/node_modules/async/concatLimit.js +++ /dev/null @@ -1,65 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -exports.default = function (coll, limit, iteratee, callback) { - callback = callback || _noop2.default; - var _iteratee = (0, _wrapAsync2.default)(iteratee); - (0, _mapLimit2.default)(coll, limit, function (val, callback) { - _iteratee(val, function (err /*, ...args*/) { - if (err) return callback(err); - return callback(null, (0, _slice2.default)(arguments, 1)); - }); - }, function (err, mapResults) { - var result = []; - for (var i = 0; i < mapResults.length; i++) { - if (mapResults[i]) { - result = _concat.apply(result, mapResults[i]); - } - } - - return callback(err, result); - }); -}; - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -var _slice = require('./internal/slice'); - -var _slice2 = _interopRequireDefault(_slice); - -var _mapLimit = require('./mapLimit'); - -var _mapLimit2 = _interopRequireDefault(_mapLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var _concat = Array.prototype.concat; - -/** - * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time. - * - * @name concatLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.concat]{@link module:Collections.concat} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, - * which should use an array as its result. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished, or an error occurs. Results is an array - * containing the concatenated results of the `iteratee` function. Invoked with - * (err, results). - */ -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/concatSeries.js b/node_modules/webpack/node_modules/async/concatSeries.js deleted file mode 100644 index 541ab7d06..000000000 --- a/node_modules/webpack/node_modules/async/concatSeries.js +++ /dev/null @@ -1,36 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -var _concatLimit = require('./concatLimit'); - -var _concatLimit2 = _interopRequireDefault(_concatLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time. - * - * @name concatSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.concat]{@link module:Collections.concat} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`. - * The iteratee should complete with an array an array of results. - * Invoked with (item, callback). - * @param {Function} [callback(err)] - A callback which is called after all the - * `iteratee` functions have finished, or an error occurs. Results is an array - * containing the concatenated results of the `iteratee` function. Invoked with - * (err, results). - */ -exports.default = (0, _doLimit2.default)(_concatLimit2.default, 1); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/constant.js b/node_modules/webpack/node_modules/async/constant.js deleted file mode 100644 index c825475bd..000000000 --- a/node_modules/webpack/node_modules/async/constant.js +++ /dev/null @@ -1,66 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -exports.default = function () /*...values*/{ - var values = (0, _slice2.default)(arguments); - var args = [null].concat(values); - return function () /*...ignoredArgs, callback*/{ - var callback = arguments[arguments.length - 1]; - return callback.apply(this, args); - }; -}; - -var _slice = require('./internal/slice'); - -var _slice2 = _interopRequireDefault(_slice); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -; - -/** - * Returns a function that when called, calls-back with the values provided. - * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to - * [`auto`]{@link module:ControlFlow.auto}. - * - * @name constant - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {...*} arguments... - Any number of arguments to automatically invoke - * callback with. - * @returns {AsyncFunction} Returns a function that when invoked, automatically - * invokes the callback with the previous given arguments. - * @example - * - * async.waterfall([ - * async.constant(42), - * function (value, next) { - * // value === 42 - * }, - * //... - * ], callback); - * - * async.waterfall([ - * async.constant(filename, "utf8"), - * fs.readFile, - * function (fileData, next) { - * //... - * } - * //... - * ], callback); - * - * async.auto({ - * hostname: async.constant("https://server.net/"), - * port: findFreePort, - * launchServer: ["hostname", "port", function (options, cb) { - * startServer(options, cb); - * }], - * //... - * }, callback); - */ -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/detect.js b/node_modules/webpack/node_modules/async/detect.js deleted file mode 100644 index db4678358..000000000 --- a/node_modules/webpack/node_modules/async/detect.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _identity = require('lodash/identity'); - -var _identity2 = _interopRequireDefault(_identity); - -var _createTester = require('./internal/createTester'); - -var _createTester2 = _interopRequireDefault(_createTester); - -var _doParallel = require('./internal/doParallel'); - -var _doParallel2 = _interopRequireDefault(_doParallel); - -var _findGetResult = require('./internal/findGetResult'); - -var _findGetResult2 = _interopRequireDefault(_findGetResult); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Returns the first value in `coll` that passes an async truth test. The - * `iteratee` is applied in parallel, meaning the first iteratee to return - * `true` will fire the detect `callback` with that result. That means the - * result might not be the first item in the original `coll` (in terms of order) - * that passes the test. - - * If order within the original `coll` is important, then look at - * [`detectSeries`]{@link module:Collections.detectSeries}. - * - * @name detect - * @static - * @memberOf module:Collections - * @method - * @alias find - * @category Collections - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. - * The iteratee must complete with a boolean value as its result. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the `iteratee` functions have finished. - * Result will be the first item in the array that passes the truth test - * (iteratee) or the value `undefined` if none passed. Invoked with - * (err, result). - * @example - * - * async.detect(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // result now equals the first file in the list that exists - * }); - */ -exports.default = (0, _doParallel2.default)((0, _createTester2.default)(_identity2.default, _findGetResult2.default)); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/detectLimit.js b/node_modules/webpack/node_modules/async/detectLimit.js deleted file mode 100644 index 6bf656022..000000000 --- a/node_modules/webpack/node_modules/async/detectLimit.js +++ /dev/null @@ -1,48 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _identity = require('lodash/identity'); - -var _identity2 = _interopRequireDefault(_identity); - -var _createTester = require('./internal/createTester'); - -var _createTester2 = _interopRequireDefault(_createTester); - -var _doParallelLimit = require('./internal/doParallelLimit'); - -var _doParallelLimit2 = _interopRequireDefault(_doParallelLimit); - -var _findGetResult = require('./internal/findGetResult'); - -var _findGetResult2 = _interopRequireDefault(_findGetResult); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a - * time. - * - * @name detectLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.detect]{@link module:Collections.detect} - * @alias findLimit - * @category Collections - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. - * The iteratee must complete with a boolean value as its result. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the `iteratee` functions have finished. - * Result will be the first item in the array that passes the truth test - * (iteratee) or the value `undefined` if none passed. Invoked with - * (err, result). - */ -exports.default = (0, _doParallelLimit2.default)((0, _createTester2.default)(_identity2.default, _findGetResult2.default)); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/detectSeries.js b/node_modules/webpack/node_modules/async/detectSeries.js deleted file mode 100644 index 6fe16c956..000000000 --- a/node_modules/webpack/node_modules/async/detectSeries.js +++ /dev/null @@ -1,38 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _detectLimit = require('./detectLimit'); - -var _detectLimit2 = _interopRequireDefault(_detectLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. - * - * @name detectSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.detect]{@link module:Collections.detect} - * @alias findSeries - * @category Collections - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. - * The iteratee must complete with a boolean value as its result. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the `iteratee` functions have finished. - * Result will be the first item in the array that passes the truth test - * (iteratee) or the value `undefined` if none passed. Invoked with - * (err, result). - */ -exports.default = (0, _doLimit2.default)(_detectLimit2.default, 1); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/dir.js b/node_modules/webpack/node_modules/async/dir.js deleted file mode 100644 index 85fbcced0..000000000 --- a/node_modules/webpack/node_modules/async/dir.js +++ /dev/null @@ -1,43 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _consoleFunc = require('./internal/consoleFunc'); - -var _consoleFunc2 = _interopRequireDefault(_consoleFunc); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Logs the result of an [`async` function]{@link AsyncFunction} to the - * `console` using `console.dir` to display the properties of the resulting object. - * Only works in Node.js or in browsers that support `console.dir` and - * `console.error` (such as FF and Chrome). - * If multiple arguments are returned from the async function, - * `console.dir` is called on each argument in order. - * - * @name dir - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} function - The function you want to eventually apply - * all arguments to. - * @param {...*} arguments... - Any number of arguments to apply to the function. - * @example - * - * // in a module - * var hello = function(name, callback) { - * setTimeout(function() { - * callback(null, {hello: name}); - * }, 1000); - * }; - * - * // in the node repl - * node> async.dir(hello, 'world'); - * {hello: 'world'} - */ -exports.default = (0, _consoleFunc2.default)('dir'); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/dist/async.js b/node_modules/webpack/node_modules/async/dist/async.js deleted file mode 100644 index ddb1af714..000000000 --- a/node_modules/webpack/node_modules/async/dist/async.js +++ /dev/null @@ -1,5595 +0,0 @@ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : - typeof define === 'function' && define.amd ? define(['exports'], factory) : - (factory((global.async = global.async || {}))); -}(this, (function (exports) { 'use strict'; - -function slice(arrayLike, start) { - start = start|0; - var newLen = Math.max(arrayLike.length - start, 0); - var newArr = Array(newLen); - for(var idx = 0; idx < newLen; idx++) { - newArr[idx] = arrayLike[start + idx]; - } - return newArr; -} - -/** - * Creates a continuation function with some arguments already applied. - * - * Useful as a shorthand when combined with other control flow functions. Any - * arguments passed to the returned function are added to the arguments - * originally passed to apply. - * - * @name apply - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {Function} fn - The function you want to eventually apply all - * arguments to. Invokes with (arguments...). - * @param {...*} arguments... - Any number of arguments to automatically apply - * when the continuation is called. - * @returns {Function} the partially-applied function - * @example - * - * // using apply - * async.parallel([ - * async.apply(fs.writeFile, 'testfile1', 'test1'), - * async.apply(fs.writeFile, 'testfile2', 'test2') - * ]); - * - * - * // the same process without using apply - * async.parallel([ - * function(callback) { - * fs.writeFile('testfile1', 'test1', callback); - * }, - * function(callback) { - * fs.writeFile('testfile2', 'test2', callback); - * } - * ]); - * - * // It's possible to pass any number of additional arguments when calling the - * // continuation: - * - * node> var fn = async.apply(sys.puts, 'one'); - * node> fn('two', 'three'); - * one - * two - * three - */ -var apply = function(fn/*, ...args*/) { - var args = slice(arguments, 1); - return function(/*callArgs*/) { - var callArgs = slice(arguments); - return fn.apply(null, args.concat(callArgs)); - }; -}; - -var initialParams = function (fn) { - return function (/*...args, callback*/) { - var args = slice(arguments); - var callback = args.pop(); - fn.call(this, args, callback); - }; -}; - -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return value != null && (type == 'object' || type == 'function'); -} - -var hasSetImmediate = typeof setImmediate === 'function' && setImmediate; -var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; - -function fallback(fn) { - setTimeout(fn, 0); -} - -function wrap(defer) { - return function (fn/*, ...args*/) { - var args = slice(arguments, 1); - defer(function () { - fn.apply(null, args); - }); - }; -} - -var _defer; - -if (hasSetImmediate) { - _defer = setImmediate; -} else if (hasNextTick) { - _defer = process.nextTick; -} else { - _defer = fallback; -} - -var setImmediate$1 = wrap(_defer); - -/** - * Take a sync function and make it async, passing its return value to a - * callback. This is useful for plugging sync functions into a waterfall, - * series, or other async functions. Any arguments passed to the generated - * function will be passed to the wrapped function (except for the final - * callback argument). Errors thrown will be passed to the callback. - * - * If the function passed to `asyncify` returns a Promise, that promises's - * resolved/rejected state will be used to call the callback, rather than simply - * the synchronous return value. - * - * This also means you can asyncify ES2017 `async` functions. - * - * @name asyncify - * @static - * @memberOf module:Utils - * @method - * @alias wrapSync - * @category Util - * @param {Function} func - The synchronous function, or Promise-returning - * function to convert to an {@link AsyncFunction}. - * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be - * invoked with `(args..., callback)`. - * @example - * - * // passing a regular synchronous function - * async.waterfall([ - * async.apply(fs.readFile, filename, "utf8"), - * async.asyncify(JSON.parse), - * function (data, next) { - * // data is the result of parsing the text. - * // If there was a parsing error, it would have been caught. - * } - * ], callback); - * - * // passing a function returning a promise - * async.waterfall([ - * async.apply(fs.readFile, filename, "utf8"), - * async.asyncify(function (contents) { - * return db.model.create(contents); - * }), - * function (model, next) { - * // `model` is the instantiated model object. - * // If there was an error, this function would be skipped. - * } - * ], callback); - * - * // es2017 example, though `asyncify` is not needed if your JS environment - * // supports async functions out of the box - * var q = async.queue(async.asyncify(async function(file) { - * var intermediateStep = await processFile(file); - * return await somePromise(intermediateStep) - * })); - * - * q.push(files); - */ -function asyncify(func) { - return initialParams(function (args, callback) { - var result; - try { - result = func.apply(this, args); - } catch (e) { - return callback(e); - } - // if result is Promise object - if (isObject(result) && typeof result.then === 'function') { - result.then(function(value) { - invokeCallback(callback, null, value); - }, function(err) { - invokeCallback(callback, err.message ? err : new Error(err)); - }); - } else { - callback(null, result); - } - }); -} - -function invokeCallback(callback, error, value) { - try { - callback(error, value); - } catch (e) { - setImmediate$1(rethrow, e); - } -} - -function rethrow(error) { - throw error; -} - -var supportsSymbol = typeof Symbol === 'function'; - -function isAsync(fn) { - return supportsSymbol && fn[Symbol.toStringTag] === 'AsyncFunction'; -} - -function wrapAsync(asyncFn) { - return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn; -} - -function applyEach$1(eachfn) { - return function(fns/*, ...args*/) { - var args = slice(arguments, 1); - var go = initialParams(function(args, callback) { - var that = this; - return eachfn(fns, function (fn, cb) { - wrapAsync(fn).apply(that, args.concat(cb)); - }, callback); - }); - if (args.length) { - return go.apply(this, args); - } - else { - return go; - } - }; -} - -/** Detect free variable `global` from Node.js. */ -var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; - -/** Detect free variable `self`. */ -var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - -/** Used as a reference to the global object. */ -var root = freeGlobal || freeSelf || Function('return this')(); - -/** Built-in value references. */ -var Symbol$1 = root.Symbol; - -/** Used for built-in method references. */ -var objectProto = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; - -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var nativeObjectToString = objectProto.toString; - -/** Built-in value references. */ -var symToStringTag$1 = Symbol$1 ? Symbol$1.toStringTag : undefined; - -/** - * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the raw `toStringTag`. - */ -function getRawTag(value) { - var isOwn = hasOwnProperty.call(value, symToStringTag$1), - tag = value[symToStringTag$1]; - - try { - value[symToStringTag$1] = undefined; - var unmasked = true; - } catch (e) {} - - var result = nativeObjectToString.call(value); - if (unmasked) { - if (isOwn) { - value[symToStringTag$1] = tag; - } else { - delete value[symToStringTag$1]; - } - } - return result; -} - -/** Used for built-in method references. */ -var objectProto$1 = Object.prototype; - -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var nativeObjectToString$1 = objectProto$1.toString; - -/** - * Converts `value` to a string using `Object.prototype.toString`. - * - * @private - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - */ -function objectToString(value) { - return nativeObjectToString$1.call(value); -} - -/** `Object#toString` result references. */ -var nullTag = '[object Null]'; -var undefinedTag = '[object Undefined]'; - -/** Built-in value references. */ -var symToStringTag = Symbol$1 ? Symbol$1.toStringTag : undefined; - -/** - * The base implementation of `getTag` without fallbacks for buggy environments. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ -function baseGetTag(value) { - if (value == null) { - return value === undefined ? undefinedTag : nullTag; - } - return (symToStringTag && symToStringTag in Object(value)) - ? getRawTag(value) - : objectToString(value); -} - -/** `Object#toString` result references. */ -var asyncTag = '[object AsyncFunction]'; -var funcTag = '[object Function]'; -var genTag = '[object GeneratorFunction]'; -var proxyTag = '[object Proxy]'; - -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction(value) { - if (!isObject(value)) { - return false; - } - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 9 which returns 'object' for typed arrays and other constructors. - var tag = baseGetTag(value); - return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; -} - -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER = 9007199254740991; - -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ -function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; -} - -/** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ -function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); -} - -// A temporary value used to identify if the loop should be broken. -// See #1064, #1293 -var breakLoop = {}; - -/** - * This method returns `undefined`. - * - * @static - * @memberOf _ - * @since 2.3.0 - * @category Util - * @example - * - * _.times(2, _.noop); - * // => [undefined, undefined] - */ -function noop() { - // No operation performed. -} - -function once(fn) { - return function () { - if (fn === null) return; - var callFn = fn; - fn = null; - callFn.apply(this, arguments); - }; -} - -var iteratorSymbol = typeof Symbol === 'function' && Symbol.iterator; - -var getIterator = function (coll) { - return iteratorSymbol && coll[iteratorSymbol] && coll[iteratorSymbol](); -}; - -/** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ -function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); - - while (++index < n) { - result[index] = iteratee(index); - } - return result; -} - -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return value != null && typeof value == 'object'; -} - -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]'; - -/** - * The base implementation of `_.isArguments`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - */ -function baseIsArguments(value) { - return isObjectLike(value) && baseGetTag(value) == argsTag; -} - -/** Used for built-in method references. */ -var objectProto$3 = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty$2 = objectProto$3.hasOwnProperty; - -/** Built-in value references. */ -var propertyIsEnumerable = objectProto$3.propertyIsEnumerable; - -/** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ -var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { - return isObjectLike(value) && hasOwnProperty$2.call(value, 'callee') && - !propertyIsEnumerable.call(value, 'callee'); -}; - -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray = Array.isArray; - -/** - * This method returns `false`. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {boolean} Returns `false`. - * @example - * - * _.times(2, _.stubFalse); - * // => [false, false] - */ -function stubFalse() { - return false; -} - -/** Detect free variable `exports`. */ -var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; - -/** Detect free variable `module`. */ -var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; - -/** Detect the popular CommonJS extension `module.exports`. */ -var moduleExports = freeModule && freeModule.exports === freeExports; - -/** Built-in value references. */ -var Buffer = moduleExports ? root.Buffer : undefined; - -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; - -/** - * Checks if `value` is a buffer. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. - * @example - * - * _.isBuffer(new Buffer(2)); - * // => true - * - * _.isBuffer(new Uint8Array(2)); - * // => false - */ -var isBuffer = nativeIsBuffer || stubFalse; - -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER$1 = 9007199254740991; - -/** Used to detect unsigned integer values. */ -var reIsUint = /^(?:0|[1-9]\d*)$/; - -/** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ -function isIndex(value, length) { - length = length == null ? MAX_SAFE_INTEGER$1 : length; - return !!length && - (typeof value == 'number' || reIsUint.test(value)) && - (value > -1 && value % 1 == 0 && value < length); -} - -/** `Object#toString` result references. */ -var argsTag$1 = '[object Arguments]'; -var arrayTag = '[object Array]'; -var boolTag = '[object Boolean]'; -var dateTag = '[object Date]'; -var errorTag = '[object Error]'; -var funcTag$1 = '[object Function]'; -var mapTag = '[object Map]'; -var numberTag = '[object Number]'; -var objectTag = '[object Object]'; -var regexpTag = '[object RegExp]'; -var setTag = '[object Set]'; -var stringTag = '[object String]'; -var weakMapTag = '[object WeakMap]'; - -var arrayBufferTag = '[object ArrayBuffer]'; -var dataViewTag = '[object DataView]'; -var float32Tag = '[object Float32Array]'; -var float64Tag = '[object Float64Array]'; -var int8Tag = '[object Int8Array]'; -var int16Tag = '[object Int16Array]'; -var int32Tag = '[object Int32Array]'; -var uint8Tag = '[object Uint8Array]'; -var uint8ClampedTag = '[object Uint8ClampedArray]'; -var uint16Tag = '[object Uint16Array]'; -var uint32Tag = '[object Uint32Array]'; - -/** Used to identify `toStringTag` values of typed arrays. */ -var typedArrayTags = {}; -typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = -typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = -typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = -typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = -typedArrayTags[uint32Tag] = true; -typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = -typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = -typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = -typedArrayTags[errorTag] = typedArrayTags[funcTag$1] = -typedArrayTags[mapTag] = typedArrayTags[numberTag] = -typedArrayTags[objectTag] = typedArrayTags[regexpTag] = -typedArrayTags[setTag] = typedArrayTags[stringTag] = -typedArrayTags[weakMapTag] = false; - -/** - * The base implementation of `_.isTypedArray` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - */ -function baseIsTypedArray(value) { - return isObjectLike(value) && - isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; -} - -/** - * The base implementation of `_.unary` without support for storing metadata. - * - * @private - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - */ -function baseUnary(func) { - return function(value) { - return func(value); - }; -} - -/** Detect free variable `exports`. */ -var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports; - -/** Detect free variable `module`. */ -var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module; - -/** Detect the popular CommonJS extension `module.exports`. */ -var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1; - -/** Detect free variable `process` from Node.js. */ -var freeProcess = moduleExports$1 && freeGlobal.process; - -/** Used to access faster Node.js helpers. */ -var nodeUtil = (function() { - try { - return freeProcess && freeProcess.binding && freeProcess.binding('util'); - } catch (e) {} -}()); - -/* Node.js helper references. */ -var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; - -/** - * Checks if `value` is classified as a typed array. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - * @example - * - * _.isTypedArray(new Uint8Array); - * // => true - * - * _.isTypedArray([]); - * // => false - */ -var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; - -/** Used for built-in method references. */ -var objectProto$2 = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty$1 = objectProto$2.hasOwnProperty; - -/** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ -function arrayLikeKeys(value, inherited) { - var isArr = isArray(value), - isArg = !isArr && isArguments(value), - isBuff = !isArr && !isArg && isBuffer(value), - isType = !isArr && !isArg && !isBuff && isTypedArray(value), - skipIndexes = isArr || isArg || isBuff || isType, - result = skipIndexes ? baseTimes(value.length, String) : [], - length = result.length; - - for (var key in value) { - if ((inherited || hasOwnProperty$1.call(value, key)) && - !(skipIndexes && ( - // Safari 9 has enumerable `arguments.length` in strict mode. - key == 'length' || - // Node.js 0.10 has enumerable non-index properties on buffers. - (isBuff && (key == 'offset' || key == 'parent')) || - // PhantomJS 2 has enumerable non-index properties on typed arrays. - (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || - // Skip index properties. - isIndex(key, length) - ))) { - result.push(key); - } - } - return result; -} - -/** Used for built-in method references. */ -var objectProto$5 = Object.prototype; - -/** - * Checks if `value` is likely a prototype object. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ -function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$5; - - return value === proto; -} - -/** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ -function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; -} - -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeKeys = overArg(Object.keys, Object); - -/** Used for built-in method references. */ -var objectProto$4 = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty$3 = objectProto$4.hasOwnProperty; - -/** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ -function baseKeys(object) { - if (!isPrototype(object)) { - return nativeKeys(object); - } - var result = []; - for (var key in Object(object)) { - if (hasOwnProperty$3.call(object, key) && key != 'constructor') { - result.push(key); - } - } - return result; -} - -/** - * Creates an array of the own enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. See the - * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * for more details. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) - * - * _.keys('hi'); - * // => ['0', '1'] - */ -function keys(object) { - return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); -} - -function createArrayIterator(coll) { - var i = -1; - var len = coll.length; - return function next() { - return ++i < len ? {value: coll[i], key: i} : null; - } -} - -function createES2015Iterator(iterator) { - var i = -1; - return function next() { - var item = iterator.next(); - if (item.done) - return null; - i++; - return {value: item.value, key: i}; - } -} - -function createObjectIterator(obj) { - var okeys = keys(obj); - var i = -1; - var len = okeys.length; - return function next() { - var key = okeys[++i]; - return i < len ? {value: obj[key], key: key} : null; - }; -} - -function iterator(coll) { - if (isArrayLike(coll)) { - return createArrayIterator(coll); - } - - var iterator = getIterator(coll); - return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); -} - -function onlyOnce(fn) { - return function() { - if (fn === null) throw new Error("Callback was already called."); - var callFn = fn; - fn = null; - callFn.apply(this, arguments); - }; -} - -function _eachOfLimit(limit) { - return function (obj, iteratee, callback) { - callback = once(callback || noop); - if (limit <= 0 || !obj) { - return callback(null); - } - var nextElem = iterator(obj); - var done = false; - var running = 0; - - function iterateeCallback(err, value) { - running -= 1; - if (err) { - done = true; - callback(err); - } - else if (value === breakLoop || (done && running <= 0)) { - done = true; - return callback(null); - } - else { - replenish(); - } - } - - function replenish () { - while (running < limit && !done) { - var elem = nextElem(); - if (elem === null) { - done = true; - if (running <= 0) { - callback(null); - } - return; - } - running += 1; - iteratee(elem.value, elem.key, onlyOnce(iterateeCallback)); - } - } - - replenish(); - }; -} - -/** - * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a - * time. - * - * @name eachOfLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.eachOf]{@link module:Collections.eachOf} - * @alias forEachOfLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each - * item in `coll`. The `key` is the item's key, or index in the case of an - * array. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - */ -function eachOfLimit(coll, limit, iteratee, callback) { - _eachOfLimit(limit)(coll, wrapAsync(iteratee), callback); -} - -function doLimit(fn, limit) { - return function (iterable, iteratee, callback) { - return fn(iterable, limit, iteratee, callback); - }; -} - -// eachOf implementation optimized for array-likes -function eachOfArrayLike(coll, iteratee, callback) { - callback = once(callback || noop); - var index = 0, - completed = 0, - length = coll.length; - if (length === 0) { - callback(null); - } - - function iteratorCallback(err, value) { - if (err) { - callback(err); - } else if ((++completed === length) || value === breakLoop) { - callback(null); - } - } - - for (; index < length; index++) { - iteratee(coll[index], index, onlyOnce(iteratorCallback)); - } -} - -// a generic version of eachOf which can handle array, object, and iterator cases. -var eachOfGeneric = doLimit(eachOfLimit, Infinity); - -/** - * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument - * to the iteratee. - * - * @name eachOf - * @static - * @memberOf module:Collections - * @method - * @alias forEachOf - * @category Collection - * @see [async.each]{@link module:Collections.each} - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each - * item in `coll`. - * The `key` is the item's key, or index in the case of an array. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - * @example - * - * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; - * var configs = {}; - * - * async.forEachOf(obj, function (value, key, callback) { - * fs.readFile(__dirname + value, "utf8", function (err, data) { - * if (err) return callback(err); - * try { - * configs[key] = JSON.parse(data); - * } catch (e) { - * return callback(e); - * } - * callback(); - * }); - * }, function (err) { - * if (err) console.error(err.message); - * // configs is now a map of JSON data - * doSomethingWith(configs); - * }); - */ -var eachOf = function(coll, iteratee, callback) { - var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric; - eachOfImplementation(coll, wrapAsync(iteratee), callback); -}; - -function doParallel(fn) { - return function (obj, iteratee, callback) { - return fn(eachOf, obj, wrapAsync(iteratee), callback); - }; -} - -function _asyncMap(eachfn, arr, iteratee, callback) { - callback = callback || noop; - arr = arr || []; - var results = []; - var counter = 0; - var _iteratee = wrapAsync(iteratee); - - eachfn(arr, function (value, _, callback) { - var index = counter++; - _iteratee(value, function (err, v) { - results[index] = v; - callback(err); - }); - }, function (err) { - callback(err, results); - }); -} - -/** - * Produces a new collection of values by mapping each value in `coll` through - * the `iteratee` function. The `iteratee` is called with an item from `coll` - * and a callback for when it has finished processing. Each of these callback - * takes 2 arguments: an `error`, and the transformed item from `coll`. If - * `iteratee` passes an error to its callback, the main `callback` (for the - * `map` function) is immediately called with the error. - * - * Note, that since this function applies the `iteratee` to each item in - * parallel, there is no guarantee that the `iteratee` functions will complete - * in order. However, the results array will be in the same order as the - * original `coll`. - * - * If `map` is passed an Object, the results will be an Array. The results - * will roughly be in the order of the original Objects' keys (but this can - * vary across JavaScript engines). - * - * @name map - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with the transformed item. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Results is an Array of the - * transformed items from the `coll`. Invoked with (err, results). - * @example - * - * async.map(['file1','file2','file3'], fs.stat, function(err, results) { - * // results is now an array of stats for each file - * }); - */ -var map = doParallel(_asyncMap); - -/** - * Applies the provided arguments to each function in the array, calling - * `callback` after all functions have completed. If you only provide the first - * argument, `fns`, then it will return a function which lets you pass in the - * arguments as if it were a single function call. If more arguments are - * provided, `callback` is required while `args` is still optional. - * - * @name applyEach - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|Object} fns - A collection of {@link AsyncFunction}s - * to all call with the same arguments - * @param {...*} [args] - any number of separate arguments to pass to the - * function. - * @param {Function} [callback] - the final argument should be the callback, - * called when all functions have completed processing. - * @returns {Function} - If only the first argument, `fns`, is provided, it will - * return a function which lets you pass in the arguments as if it were a single - * function call. The signature is `(..args, callback)`. If invoked with any - * arguments, `callback` is required. - * @example - * - * async.applyEach([enableSearch, updateSchema], 'bucket', callback); - * - * // partial application example: - * async.each( - * buckets, - * async.applyEach([enableSearch, updateSchema]), - * callback - * ); - */ -var applyEach = applyEach$1(map); - -function doParallelLimit(fn) { - return function (obj, limit, iteratee, callback) { - return fn(_eachOfLimit(limit), obj, wrapAsync(iteratee), callback); - }; -} - -/** - * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time. - * - * @name mapLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.map]{@link module:Collections.map} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with the transformed item. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Results is an array of the - * transformed items from the `coll`. Invoked with (err, results). - */ -var mapLimit = doParallelLimit(_asyncMap); - -/** - * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time. - * - * @name mapSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.map]{@link module:Collections.map} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with the transformed item. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Results is an array of the - * transformed items from the `coll`. Invoked with (err, results). - */ -var mapSeries = doLimit(mapLimit, 1); - -/** - * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time. - * - * @name applyEachSeries - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.applyEach]{@link module:ControlFlow.applyEach} - * @category Control Flow - * @param {Array|Iterable|Object} fns - A collection of {@link AsyncFunction}s to all - * call with the same arguments - * @param {...*} [args] - any number of separate arguments to pass to the - * function. - * @param {Function} [callback] - the final argument should be the callback, - * called when all functions have completed processing. - * @returns {Function} - If only the first argument is provided, it will return - * a function which lets you pass in the arguments as if it were a single - * function call. - */ -var applyEachSeries = applyEach$1(mapSeries); - -/** - * A specialized version of `_.forEach` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns `array`. - */ -function arrayEach(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length; - - while (++index < length) { - if (iteratee(array[index], index, array) === false) { - break; - } - } - return array; -} - -/** - * Creates a base function for methods like `_.forIn` and `_.forOwn`. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ -function createBaseFor(fromRight) { - return function(object, iteratee, keysFunc) { - var index = -1, - iterable = Object(object), - props = keysFunc(object), - length = props.length; - - while (length--) { - var key = props[fromRight ? length : ++index]; - if (iteratee(iterable[key], key, iterable) === false) { - break; - } - } - return object; - }; -} - -/** - * The base implementation of `baseForOwn` which iterates over `object` - * properties returned by `keysFunc` and invokes `iteratee` for each property. - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ -var baseFor = createBaseFor(); - -/** - * The base implementation of `_.forOwn` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ -function baseForOwn(object, iteratee) { - return object && baseFor(object, iteratee, keys); -} - -/** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {number} fromIndex The index to search from. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseFindIndex(array, predicate, fromIndex, fromRight) { - var length = array.length, - index = fromIndex + (fromRight ? 1 : -1); - - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } - } - return -1; -} - -/** - * The base implementation of `_.isNaN` without support for number objects. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - */ -function baseIsNaN(value) { - return value !== value; -} - -/** - * A specialized version of `_.indexOf` which performs strict equality - * comparisons of values, i.e. `===`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function strictIndexOf(array, value, fromIndex) { - var index = fromIndex - 1, - length = array.length; - - while (++index < length) { - if (array[index] === value) { - return index; - } - } - return -1; -} - -/** - * The base implementation of `_.indexOf` without `fromIndex` bounds checks. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseIndexOf(array, value, fromIndex) { - return value === value - ? strictIndexOf(array, value, fromIndex) - : baseFindIndex(array, baseIsNaN, fromIndex); -} - -/** - * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on - * their requirements. Each function can optionally depend on other functions - * being completed first, and each function is run as soon as its requirements - * are satisfied. - * - * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence - * will stop. Further tasks will not execute (so any other functions depending - * on it will not run), and the main `callback` is immediately called with the - * error. - * - * {@link AsyncFunction}s also receive an object containing the results of functions which - * have completed so far as the first argument, if they have dependencies. If a - * task function has no dependencies, it will only be passed a callback. - * - * @name auto - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Object} tasks - An object. Each of its properties is either a - * function or an array of requirements, with the {@link AsyncFunction} itself the last item - * in the array. The object's key of a property serves as the name of the task - * defined by that property, i.e. can be used when specifying requirements for - * other tasks. The function receives one or two arguments: - * * a `results` object, containing the results of the previously executed - * functions, only passed if the task has any dependencies, - * * a `callback(err, result)` function, which must be called when finished, - * passing an `error` (which can be `null`) and the result of the function's - * execution. - * @param {number} [concurrency=Infinity] - An optional `integer` for - * determining the maximum number of tasks that can be run in parallel. By - * default, as many as possible. - * @param {Function} [callback] - An optional callback which is called when all - * the tasks have been completed. It receives the `err` argument if any `tasks` - * pass an error to their callback. Results are always returned; however, if an - * error occurs, no further `tasks` will be performed, and the results object - * will only contain partial results. Invoked with (err, results). - * @returns undefined - * @example - * - * async.auto({ - * // this function will just be passed a callback - * readData: async.apply(fs.readFile, 'data.txt', 'utf-8'), - * showData: ['readData', function(results, cb) { - * // results.readData is the file's contents - * // ... - * }] - * }, callback); - * - * async.auto({ - * get_data: function(callback) { - * console.log('in get_data'); - * // async code to get some data - * callback(null, 'data', 'converted to array'); - * }, - * make_folder: function(callback) { - * console.log('in make_folder'); - * // async code to create a directory to store a file in - * // this is run at the same time as getting the data - * callback(null, 'folder'); - * }, - * write_file: ['get_data', 'make_folder', function(results, callback) { - * console.log('in write_file', JSON.stringify(results)); - * // once there is some data and the directory exists, - * // write the data to a file in the directory - * callback(null, 'filename'); - * }], - * email_link: ['write_file', function(results, callback) { - * console.log('in email_link', JSON.stringify(results)); - * // once the file is written let's email a link to it... - * // results.write_file contains the filename returned by write_file. - * callback(null, {'file':results.write_file, 'email':'user@example.com'}); - * }] - * }, function(err, results) { - * console.log('err = ', err); - * console.log('results = ', results); - * }); - */ -var auto = function (tasks, concurrency, callback) { - if (typeof concurrency === 'function') { - // concurrency is optional, shift the args. - callback = concurrency; - concurrency = null; - } - callback = once(callback || noop); - var keys$$1 = keys(tasks); - var numTasks = keys$$1.length; - if (!numTasks) { - return callback(null); - } - if (!concurrency) { - concurrency = numTasks; - } - - var results = {}; - var runningTasks = 0; - var hasError = false; - - var listeners = Object.create(null); - - var readyTasks = []; - - // for cycle detection: - var readyToCheck = []; // tasks that have been identified as reachable - // without the possibility of returning to an ancestor task - var uncheckedDependencies = {}; - - baseForOwn(tasks, function (task, key) { - if (!isArray(task)) { - // no dependencies - enqueueTask(key, [task]); - readyToCheck.push(key); - return; - } - - var dependencies = task.slice(0, task.length - 1); - var remainingDependencies = dependencies.length; - if (remainingDependencies === 0) { - enqueueTask(key, task); - readyToCheck.push(key); - return; - } - uncheckedDependencies[key] = remainingDependencies; - - arrayEach(dependencies, function (dependencyName) { - if (!tasks[dependencyName]) { - throw new Error('async.auto task `' + key + - '` has a non-existent dependency `' + - dependencyName + '` in ' + - dependencies.join(', ')); - } - addListener(dependencyName, function () { - remainingDependencies--; - if (remainingDependencies === 0) { - enqueueTask(key, task); - } - }); - }); - }); - - checkForDeadlocks(); - processQueue(); - - function enqueueTask(key, task) { - readyTasks.push(function () { - runTask(key, task); - }); - } - - function processQueue() { - if (readyTasks.length === 0 && runningTasks === 0) { - return callback(null, results); - } - while(readyTasks.length && runningTasks < concurrency) { - var run = readyTasks.shift(); - run(); - } - - } - - function addListener(taskName, fn) { - var taskListeners = listeners[taskName]; - if (!taskListeners) { - taskListeners = listeners[taskName] = []; - } - - taskListeners.push(fn); - } - - function taskComplete(taskName) { - var taskListeners = listeners[taskName] || []; - arrayEach(taskListeners, function (fn) { - fn(); - }); - processQueue(); - } - - - function runTask(key, task) { - if (hasError) return; - - var taskCallback = onlyOnce(function(err, result) { - runningTasks--; - if (arguments.length > 2) { - result = slice(arguments, 1); - } - if (err) { - var safeResults = {}; - baseForOwn(results, function(val, rkey) { - safeResults[rkey] = val; - }); - safeResults[key] = result; - hasError = true; - listeners = Object.create(null); - - callback(err, safeResults); - } else { - results[key] = result; - taskComplete(key); - } - }); - - runningTasks++; - var taskFn = wrapAsync(task[task.length - 1]); - if (task.length > 1) { - taskFn(results, taskCallback); - } else { - taskFn(taskCallback); - } - } - - function checkForDeadlocks() { - // Kahn's algorithm - // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm - // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html - var currentTask; - var counter = 0; - while (readyToCheck.length) { - currentTask = readyToCheck.pop(); - counter++; - arrayEach(getDependents(currentTask), function (dependent) { - if (--uncheckedDependencies[dependent] === 0) { - readyToCheck.push(dependent); - } - }); - } - - if (counter !== numTasks) { - throw new Error( - 'async.auto cannot execute tasks due to a recursive dependency' - ); - } - } - - function getDependents(taskName) { - var result = []; - baseForOwn(tasks, function (task, key) { - if (isArray(task) && baseIndexOf(task, taskName, 0) >= 0) { - result.push(key); - } - }); - return result; - } -}; - -/** - * A specialized version of `_.map` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ -function arrayMap(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length, - result = Array(length); - - while (++index < length) { - result[index] = iteratee(array[index], index, array); - } - return result; -} - -/** `Object#toString` result references. */ -var symbolTag = '[object Symbol]'; - -/** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ -function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && baseGetTag(value) == symbolTag); -} - -/** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0; - -/** Used to convert symbols to primitives and strings. */ -var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined; -var symbolToString = symbolProto ? symbolProto.toString : undefined; - -/** - * The base implementation of `_.toString` which doesn't convert nullish - * values to empty strings. - * - * @private - * @param {*} value The value to process. - * @returns {string} Returns the string. - */ -function baseToString(value) { - // Exit early for strings to avoid a performance hit in some environments. - if (typeof value == 'string') { - return value; - } - if (isArray(value)) { - // Recursively convert values (susceptible to call stack limits). - return arrayMap(value, baseToString) + ''; - } - if (isSymbol(value)) { - return symbolToString ? symbolToString.call(value) : ''; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; -} - -/** - * The base implementation of `_.slice` without an iteratee call guard. - * - * @private - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ -function baseSlice(array, start, end) { - var index = -1, - length = array.length; - - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = end > length ? length : end; - if (end < 0) { - end += length; - } - length = start > end ? 0 : ((end - start) >>> 0); - start >>>= 0; - - var result = Array(length); - while (++index < length) { - result[index] = array[index + start]; - } - return result; -} - -/** - * Casts `array` to a slice if it's needed. - * - * @private - * @param {Array} array The array to inspect. - * @param {number} start The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the cast slice. - */ -function castSlice(array, start, end) { - var length = array.length; - end = end === undefined ? length : end; - return (!start && end >= length) ? array : baseSlice(array, start, end); -} - -/** - * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the last unmatched string symbol. - */ -function charsEndIndex(strSymbols, chrSymbols) { - var index = strSymbols.length; - - while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; -} - -/** - * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the first unmatched string symbol. - */ -function charsStartIndex(strSymbols, chrSymbols) { - var index = -1, - length = strSymbols.length; - - while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; -} - -/** - * Converts an ASCII `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function asciiToArray(string) { - return string.split(''); -} - -/** Used to compose unicode character classes. */ -var rsAstralRange = '\\ud800-\\udfff'; -var rsComboMarksRange = '\\u0300-\\u036f'; -var reComboHalfMarksRange = '\\ufe20-\\ufe2f'; -var rsComboSymbolsRange = '\\u20d0-\\u20ff'; -var rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange; -var rsVarRange = '\\ufe0e\\ufe0f'; - -/** Used to compose unicode capture groups. */ -var rsZWJ = '\\u200d'; - -/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ -var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); - -/** - * Checks if `string` contains Unicode symbols. - * - * @private - * @param {string} string The string to inspect. - * @returns {boolean} Returns `true` if a symbol is found, else `false`. - */ -function hasUnicode(string) { - return reHasUnicode.test(string); -} - -/** Used to compose unicode character classes. */ -var rsAstralRange$1 = '\\ud800-\\udfff'; -var rsComboMarksRange$1 = '\\u0300-\\u036f'; -var reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f'; -var rsComboSymbolsRange$1 = '\\u20d0-\\u20ff'; -var rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1; -var rsVarRange$1 = '\\ufe0e\\ufe0f'; - -/** Used to compose unicode capture groups. */ -var rsAstral = '[' + rsAstralRange$1 + ']'; -var rsCombo = '[' + rsComboRange$1 + ']'; -var rsFitz = '\\ud83c[\\udffb-\\udfff]'; -var rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')'; -var rsNonAstral = '[^' + rsAstralRange$1 + ']'; -var rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}'; -var rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]'; -var rsZWJ$1 = '\\u200d'; - -/** Used to compose unicode regexes. */ -var reOptMod = rsModifier + '?'; -var rsOptVar = '[' + rsVarRange$1 + ']?'; -var rsOptJoin = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*'; -var rsSeq = rsOptVar + reOptMod + rsOptJoin; -var rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; - -/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ -var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); - -/** - * Converts a Unicode `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function unicodeToArray(string) { - return string.match(reUnicode) || []; -} - -/** - * Converts `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function stringToArray(string) { - return hasUnicode(string) - ? unicodeToArray(string) - : asciiToArray(string); -} - -/** - * Converts `value` to a string. An empty string is returned for `null` - * and `undefined` values. The sign of `-0` is preserved. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - * @example - * - * _.toString(null); - * // => '' - * - * _.toString(-0); - * // => '-0' - * - * _.toString([1, 2, 3]); - * // => '1,2,3' - */ -function toString(value) { - return value == null ? '' : baseToString(value); -} - -/** Used to match leading and trailing whitespace. */ -var reTrim = /^\s+|\s+$/g; - -/** - * Removes leading and trailing whitespace or specified characters from `string`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to trim. - * @param {string} [chars=whitespace] The characters to trim. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {string} Returns the trimmed string. - * @example - * - * _.trim(' abc '); - * // => 'abc' - * - * _.trim('-_-abc-_-', '_-'); - * // => 'abc' - * - * _.map([' foo ', ' bar '], _.trim); - * // => ['foo', 'bar'] - */ -function trim(string, chars, guard) { - string = toString(string); - if (string && (guard || chars === undefined)) { - return string.replace(reTrim, ''); - } - if (!string || !(chars = baseToString(chars))) { - return string; - } - var strSymbols = stringToArray(string), - chrSymbols = stringToArray(chars), - start = charsStartIndex(strSymbols, chrSymbols), - end = charsEndIndex(strSymbols, chrSymbols) + 1; - - return castSlice(strSymbols, start, end).join(''); -} - -var FN_ARGS = /^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m; -var FN_ARG_SPLIT = /,/; -var FN_ARG = /(=.+)?(\s*)$/; -var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; - -function parseParams(func) { - func = func.toString().replace(STRIP_COMMENTS, ''); - func = func.match(FN_ARGS)[2].replace(' ', ''); - func = func ? func.split(FN_ARG_SPLIT) : []; - func = func.map(function (arg){ - return trim(arg.replace(FN_ARG, '')); - }); - return func; -} - -/** - * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent - * tasks are specified as parameters to the function, after the usual callback - * parameter, with the parameter names matching the names of the tasks it - * depends on. This can provide even more readable task graphs which can be - * easier to maintain. - * - * If a final callback is specified, the task results are similarly injected, - * specified as named parameters after the initial error parameter. - * - * The autoInject function is purely syntactic sugar and its semantics are - * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}. - * - * @name autoInject - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.auto]{@link module:ControlFlow.auto} - * @category Control Flow - * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of - * the form 'func([dependencies...], callback). The object's key of a property - * serves as the name of the task defined by that property, i.e. can be used - * when specifying requirements for other tasks. - * * The `callback` parameter is a `callback(err, result)` which must be called - * when finished, passing an `error` (which can be `null`) and the result of - * the function's execution. The remaining parameters name other tasks on - * which the task is dependent, and the results from those tasks are the - * arguments of those parameters. - * @param {Function} [callback] - An optional callback which is called when all - * the tasks have been completed. It receives the `err` argument if any `tasks` - * pass an error to their callback, and a `results` object with any completed - * task results, similar to `auto`. - * @example - * - * // The example from `auto` can be rewritten as follows: - * async.autoInject({ - * get_data: function(callback) { - * // async code to get some data - * callback(null, 'data', 'converted to array'); - * }, - * make_folder: function(callback) { - * // async code to create a directory to store a file in - * // this is run at the same time as getting the data - * callback(null, 'folder'); - * }, - * write_file: function(get_data, make_folder, callback) { - * // once there is some data and the directory exists, - * // write the data to a file in the directory - * callback(null, 'filename'); - * }, - * email_link: function(write_file, callback) { - * // once the file is written let's email a link to it... - * // write_file contains the filename returned by write_file. - * callback(null, {'file':write_file, 'email':'user@example.com'}); - * } - * }, function(err, results) { - * console.log('err = ', err); - * console.log('email_link = ', results.email_link); - * }); - * - * // If you are using a JS minifier that mangles parameter names, `autoInject` - * // will not work with plain functions, since the parameter names will be - * // collapsed to a single letter identifier. To work around this, you can - * // explicitly specify the names of the parameters your task function needs - * // in an array, similar to Angular.js dependency injection. - * - * // This still has an advantage over plain `auto`, since the results a task - * // depends on are still spread into arguments. - * async.autoInject({ - * //... - * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) { - * callback(null, 'filename'); - * }], - * email_link: ['write_file', function(write_file, callback) { - * callback(null, {'file':write_file, 'email':'user@example.com'}); - * }] - * //... - * }, function(err, results) { - * console.log('err = ', err); - * console.log('email_link = ', results.email_link); - * }); - */ -function autoInject(tasks, callback) { - var newTasks = {}; - - baseForOwn(tasks, function (taskFn, key) { - var params; - var fnIsAsync = isAsync(taskFn); - var hasNoDeps = - (!fnIsAsync && taskFn.length === 1) || - (fnIsAsync && taskFn.length === 0); - - if (isArray(taskFn)) { - params = taskFn.slice(0, -1); - taskFn = taskFn[taskFn.length - 1]; - - newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn); - } else if (hasNoDeps) { - // no dependencies, use the function as-is - newTasks[key] = taskFn; - } else { - params = parseParams(taskFn); - if (taskFn.length === 0 && !fnIsAsync && params.length === 0) { - throw new Error("autoInject task functions require explicit parameters."); - } - - // remove callback param - if (!fnIsAsync) params.pop(); - - newTasks[key] = params.concat(newTask); - } - - function newTask(results, taskCb) { - var newArgs = arrayMap(params, function (name) { - return results[name]; - }); - newArgs.push(taskCb); - wrapAsync(taskFn).apply(null, newArgs); - } - }); - - auto(newTasks, callback); -} - -// Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation -// used for queues. This implementation assumes that the node provided by the user can be modified -// to adjust the next and last properties. We implement only the minimal functionality -// for queue support. -function DLL() { - this.head = this.tail = null; - this.length = 0; -} - -function setInitial(dll, node) { - dll.length = 1; - dll.head = dll.tail = node; -} - -DLL.prototype.removeLink = function(node) { - if (node.prev) node.prev.next = node.next; - else this.head = node.next; - if (node.next) node.next.prev = node.prev; - else this.tail = node.prev; - - node.prev = node.next = null; - this.length -= 1; - return node; -}; - -DLL.prototype.empty = function () { - while(this.head) this.shift(); - return this; -}; - -DLL.prototype.insertAfter = function(node, newNode) { - newNode.prev = node; - newNode.next = node.next; - if (node.next) node.next.prev = newNode; - else this.tail = newNode; - node.next = newNode; - this.length += 1; -}; - -DLL.prototype.insertBefore = function(node, newNode) { - newNode.prev = node.prev; - newNode.next = node; - if (node.prev) node.prev.next = newNode; - else this.head = newNode; - node.prev = newNode; - this.length += 1; -}; - -DLL.prototype.unshift = function(node) { - if (this.head) this.insertBefore(this.head, node); - else setInitial(this, node); -}; - -DLL.prototype.push = function(node) { - if (this.tail) this.insertAfter(this.tail, node); - else setInitial(this, node); -}; - -DLL.prototype.shift = function() { - return this.head && this.removeLink(this.head); -}; - -DLL.prototype.pop = function() { - return this.tail && this.removeLink(this.tail); -}; - -DLL.prototype.toArray = function () { - var arr = Array(this.length); - var curr = this.head; - for(var idx = 0; idx < this.length; idx++) { - arr[idx] = curr.data; - curr = curr.next; - } - return arr; -}; - -DLL.prototype.remove = function (testFn) { - var curr = this.head; - while(!!curr) { - var next = curr.next; - if (testFn(curr)) { - this.removeLink(curr); - } - curr = next; - } - return this; -}; - -function queue(worker, concurrency, payload) { - if (concurrency == null) { - concurrency = 1; - } - else if(concurrency === 0) { - throw new Error('Concurrency must not be zero'); - } - - var _worker = wrapAsync(worker); - var numRunning = 0; - var workersList = []; - - var processingScheduled = false; - function _insert(data, insertAtFront, callback) { - if (callback != null && typeof callback !== 'function') { - throw new Error('task callback must be a function'); - } - q.started = true; - if (!isArray(data)) { - data = [data]; - } - if (data.length === 0 && q.idle()) { - // call drain immediately if there are no tasks - return setImmediate$1(function() { - q.drain(); - }); - } - - for (var i = 0, l = data.length; i < l; i++) { - var item = { - data: data[i], - callback: callback || noop - }; - - if (insertAtFront) { - q._tasks.unshift(item); - } else { - q._tasks.push(item); - } - } - - if (!processingScheduled) { - processingScheduled = true; - setImmediate$1(function() { - processingScheduled = false; - q.process(); - }); - } - } - - function _next(tasks) { - return function(err){ - numRunning -= 1; - - for (var i = 0, l = tasks.length; i < l; i++) { - var task = tasks[i]; - - var index = baseIndexOf(workersList, task, 0); - if (index === 0) { - workersList.shift(); - } else if (index > 0) { - workersList.splice(index, 1); - } - - task.callback.apply(task, arguments); - - if (err != null) { - q.error(err, task.data); - } - } - - if (numRunning <= (q.concurrency - q.buffer) ) { - q.unsaturated(); - } - - if (q.idle()) { - q.drain(); - } - q.process(); - }; - } - - var isProcessing = false; - var q = { - _tasks: new DLL(), - concurrency: concurrency, - payload: payload, - saturated: noop, - unsaturated:noop, - buffer: concurrency / 4, - empty: noop, - drain: noop, - error: noop, - started: false, - paused: false, - push: function (data, callback) { - _insert(data, false, callback); - }, - kill: function () { - q.drain = noop; - q._tasks.empty(); - }, - unshift: function (data, callback) { - _insert(data, true, callback); - }, - remove: function (testFn) { - q._tasks.remove(testFn); - }, - process: function () { - // Avoid trying to start too many processing operations. This can occur - // when callbacks resolve synchronously (#1267). - if (isProcessing) { - return; - } - isProcessing = true; - while(!q.paused && numRunning < q.concurrency && q._tasks.length){ - var tasks = [], data = []; - var l = q._tasks.length; - if (q.payload) l = Math.min(l, q.payload); - for (var i = 0; i < l; i++) { - var node = q._tasks.shift(); - tasks.push(node); - workersList.push(node); - data.push(node.data); - } - - numRunning += 1; - - if (q._tasks.length === 0) { - q.empty(); - } - - if (numRunning === q.concurrency) { - q.saturated(); - } - - var cb = onlyOnce(_next(tasks)); - _worker(data, cb); - } - isProcessing = false; - }, - length: function () { - return q._tasks.length; - }, - running: function () { - return numRunning; - }, - workersList: function () { - return workersList; - }, - idle: function() { - return q._tasks.length + numRunning === 0; - }, - pause: function () { - q.paused = true; - }, - resume: function () { - if (q.paused === false) { return; } - q.paused = false; - setImmediate$1(q.process); - } - }; - return q; -} - -/** - * A cargo of tasks for the worker function to complete. Cargo inherits all of - * the same methods and event callbacks as [`queue`]{@link module:ControlFlow.queue}. - * @typedef {Object} CargoObject - * @memberOf module:ControlFlow - * @property {Function} length - A function returning the number of items - * waiting to be processed. Invoke like `cargo.length()`. - * @property {number} payload - An `integer` for determining how many tasks - * should be process per round. This property can be changed after a `cargo` is - * created to alter the payload on-the-fly. - * @property {Function} push - Adds `task` to the `queue`. The callback is - * called once the `worker` has finished processing the task. Instead of a - * single task, an array of `tasks` can be submitted. The respective callback is - * used for every task in the list. Invoke like `cargo.push(task, [callback])`. - * @property {Function} saturated - A callback that is called when the - * `queue.length()` hits the concurrency and further tasks will be queued. - * @property {Function} empty - A callback that is called when the last item - * from the `queue` is given to a `worker`. - * @property {Function} drain - A callback that is called when the last item - * from the `queue` has returned from the `worker`. - * @property {Function} idle - a function returning false if there are items - * waiting or being processed, or true if not. Invoke like `cargo.idle()`. - * @property {Function} pause - a function that pauses the processing of tasks - * until `resume()` is called. Invoke like `cargo.pause()`. - * @property {Function} resume - a function that resumes the processing of - * queued tasks when the queue is paused. Invoke like `cargo.resume()`. - * @property {Function} kill - a function that removes the `drain` callback and - * empties remaining tasks from the queue forcing it to go idle. Invoke like `cargo.kill()`. - */ - -/** - * Creates a `cargo` object with the specified payload. Tasks added to the - * cargo will be processed altogether (up to the `payload` limit). If the - * `worker` is in progress, the task is queued until it becomes available. Once - * the `worker` has completed some tasks, each callback of those tasks is - * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) - * for how `cargo` and `queue` work. - * - * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers - * at a time, cargo passes an array of tasks to a single worker, repeating - * when the worker is finished. - * - * @name cargo - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.queue]{@link module:ControlFlow.queue} - * @category Control Flow - * @param {AsyncFunction} worker - An asynchronous function for processing an array - * of queued tasks. Invoked with `(tasks, callback)`. - * @param {number} [payload=Infinity] - An optional `integer` for determining - * how many tasks should be processed per round; if omitted, the default is - * unlimited. - * @returns {module:ControlFlow.CargoObject} A cargo object to manage the tasks. Callbacks can - * attached as certain properties to listen for specific events during the - * lifecycle of the cargo and inner queue. - * @example - * - * // create a cargo object with payload 2 - * var cargo = async.cargo(function(tasks, callback) { - * for (var i=0; i<tasks.length; i++) { - * console.log('hello ' + tasks[i].name); - * } - * callback(); - * }, 2); - * - * // add some items - * cargo.push({name: 'foo'}, function(err) { - * console.log('finished processing foo'); - * }); - * cargo.push({name: 'bar'}, function(err) { - * console.log('finished processing bar'); - * }); - * cargo.push({name: 'baz'}, function(err) { - * console.log('finished processing baz'); - * }); - */ -function cargo(worker, payload) { - return queue(worker, 1, payload); -} - -/** - * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. - * - * @name eachOfSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.eachOf]{@link module:Collections.eachOf} - * @alias forEachOfSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Invoked with (err). - */ -var eachOfSeries = doLimit(eachOfLimit, 1); - -/** - * Reduces `coll` into a single value using an async `iteratee` to return each - * successive step. `memo` is the initial state of the reduction. This function - * only operates in series. - * - * For performance reasons, it may make sense to split a call to this function - * into a parallel map, and then use the normal `Array.prototype.reduce` on the - * results. This function is for situations where each step in the reduction - * needs to be async; if you can get the data before reducing it, then it's - * probably a good idea to do so. - * - * @name reduce - * @static - * @memberOf module:Collections - * @method - * @alias inject - * @alias foldl - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {*} memo - The initial state of the reduction. - * @param {AsyncFunction} iteratee - A function applied to each item in the - * array to produce the next step in the reduction. - * The `iteratee` should complete with the next state of the reduction. - * If the iteratee complete with an error, the reduction is stopped and the - * main `callback` is immediately called with the error. - * Invoked with (memo, item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result is the reduced value. Invoked with - * (err, result). - * @example - * - * async.reduce([1,2,3], 0, function(memo, item, callback) { - * // pointless async: - * process.nextTick(function() { - * callback(null, memo + item) - * }); - * }, function(err, result) { - * // result is now equal to the last value of memo, which is 6 - * }); - */ -function reduce(coll, memo, iteratee, callback) { - callback = once(callback || noop); - var _iteratee = wrapAsync(iteratee); - eachOfSeries(coll, function(x, i, callback) { - _iteratee(memo, x, function(err, v) { - memo = v; - callback(err); - }); - }, function(err) { - callback(err, memo); - }); -} - -/** - * Version of the compose function that is more natural to read. Each function - * consumes the return value of the previous function. It is the equivalent of - * [compose]{@link module:ControlFlow.compose} with the arguments reversed. - * - * Each function is executed with the `this` binding of the composed function. - * - * @name seq - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.compose]{@link module:ControlFlow.compose} - * @category Control Flow - * @param {...AsyncFunction} functions - the asynchronous functions to compose - * @returns {Function} a function that composes the `functions` in order - * @example - * - * // Requires lodash (or underscore), express3 and dresende's orm2. - * // Part of an app, that fetches cats of the logged user. - * // This example uses `seq` function to avoid overnesting and error - * // handling clutter. - * app.get('/cats', function(request, response) { - * var User = request.models.User; - * async.seq( - * _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data)) - * function(user, fn) { - * user.getCats(fn); // 'getCats' has signature (callback(err, data)) - * } - * )(req.session.user_id, function (err, cats) { - * if (err) { - * console.error(err); - * response.json({ status: 'error', message: err.message }); - * } else { - * response.json({ status: 'ok', message: 'Cats found', data: cats }); - * } - * }); - * }); - */ -function seq(/*...functions*/) { - var _functions = arrayMap(arguments, wrapAsync); - return function(/*...args*/) { - var args = slice(arguments); - var that = this; - - var cb = args[args.length - 1]; - if (typeof cb == 'function') { - args.pop(); - } else { - cb = noop; - } - - reduce(_functions, args, function(newargs, fn, cb) { - fn.apply(that, newargs.concat(function(err/*, ...nextargs*/) { - var nextargs = slice(arguments, 1); - cb(err, nextargs); - })); - }, - function(err, results) { - cb.apply(that, [err].concat(results)); - }); - }; -} - -/** - * Creates a function which is a composition of the passed asynchronous - * functions. Each function consumes the return value of the function that - * follows. Composing functions `f()`, `g()`, and `h()` would produce the result - * of `f(g(h()))`, only this version uses callbacks to obtain the return values. - * - * Each function is executed with the `this` binding of the composed function. - * - * @name compose - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {...AsyncFunction} functions - the asynchronous functions to compose - * @returns {Function} an asynchronous function that is the composed - * asynchronous `functions` - * @example - * - * function add1(n, callback) { - * setTimeout(function () { - * callback(null, n + 1); - * }, 10); - * } - * - * function mul3(n, callback) { - * setTimeout(function () { - * callback(null, n * 3); - * }, 10); - * } - * - * var add1mul3 = async.compose(mul3, add1); - * add1mul3(4, function (err, result) { - * // result now equals 15 - * }); - */ -var compose = function(/*...args*/) { - return seq.apply(null, slice(arguments).reverse()); -}; - -var _concat = Array.prototype.concat; - -/** - * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time. - * - * @name concatLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.concat]{@link module:Collections.concat} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, - * which should use an array as its result. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished, or an error occurs. Results is an array - * containing the concatenated results of the `iteratee` function. Invoked with - * (err, results). - */ -var concatLimit = function(coll, limit, iteratee, callback) { - callback = callback || noop; - var _iteratee = wrapAsync(iteratee); - mapLimit(coll, limit, function(val, callback) { - _iteratee(val, function(err /*, ...args*/) { - if (err) return callback(err); - return callback(null, slice(arguments, 1)); - }); - }, function(err, mapResults) { - var result = []; - for (var i = 0; i < mapResults.length; i++) { - if (mapResults[i]) { - result = _concat.apply(result, mapResults[i]); - } - } - - return callback(err, result); - }); -}; - -/** - * Applies `iteratee` to each item in `coll`, concatenating the results. Returns - * the concatenated list. The `iteratee`s are called in parallel, and the - * results are concatenated as they return. There is no guarantee that the - * results array will be returned in the original order of `coll` passed to the - * `iteratee` function. - * - * @name concat - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, - * which should use an array as its result. Invoked with (item, callback). - * @param {Function} [callback(err)] - A callback which is called after all the - * `iteratee` functions have finished, or an error occurs. Results is an array - * containing the concatenated results of the `iteratee` function. Invoked with - * (err, results). - * @example - * - * async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files) { - * // files is now a list of filenames that exist in the 3 directories - * }); - */ -var concat = doLimit(concatLimit, Infinity); - -/** - * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time. - * - * @name concatSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.concat]{@link module:Collections.concat} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`. - * The iteratee should complete with an array an array of results. - * Invoked with (item, callback). - * @param {Function} [callback(err)] - A callback which is called after all the - * `iteratee` functions have finished, or an error occurs. Results is an array - * containing the concatenated results of the `iteratee` function. Invoked with - * (err, results). - */ -var concatSeries = doLimit(concatLimit, 1); - -/** - * Returns a function that when called, calls-back with the values provided. - * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to - * [`auto`]{@link module:ControlFlow.auto}. - * - * @name constant - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {...*} arguments... - Any number of arguments to automatically invoke - * callback with. - * @returns {AsyncFunction} Returns a function that when invoked, automatically - * invokes the callback with the previous given arguments. - * @example - * - * async.waterfall([ - * async.constant(42), - * function (value, next) { - * // value === 42 - * }, - * //... - * ], callback); - * - * async.waterfall([ - * async.constant(filename, "utf8"), - * fs.readFile, - * function (fileData, next) { - * //... - * } - * //... - * ], callback); - * - * async.auto({ - * hostname: async.constant("https://server.net/"), - * port: findFreePort, - * launchServer: ["hostname", "port", function (options, cb) { - * startServer(options, cb); - * }], - * //... - * }, callback); - */ -var constant = function(/*...values*/) { - var values = slice(arguments); - var args = [null].concat(values); - return function (/*...ignoredArgs, callback*/) { - var callback = arguments[arguments.length - 1]; - return callback.apply(this, args); - }; -}; - -/** - * This method returns the first argument it receives. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Util - * @param {*} value Any value. - * @returns {*} Returns `value`. - * @example - * - * var object = { 'a': 1 }; - * - * console.log(_.identity(object) === object); - * // => true - */ -function identity(value) { - return value; -} - -function _createTester(check, getResult) { - return function(eachfn, arr, iteratee, cb) { - cb = cb || noop; - var testPassed = false; - var testResult; - eachfn(arr, function(value, _, callback) { - iteratee(value, function(err, result) { - if (err) { - callback(err); - } else if (check(result) && !testResult) { - testPassed = true; - testResult = getResult(true, value); - callback(null, breakLoop); - } else { - callback(); - } - }); - }, function(err) { - if (err) { - cb(err); - } else { - cb(null, testPassed ? testResult : getResult(false)); - } - }); - }; -} - -function _findGetResult(v, x) { - return x; -} - -/** - * Returns the first value in `coll` that passes an async truth test. The - * `iteratee` is applied in parallel, meaning the first iteratee to return - * `true` will fire the detect `callback` with that result. That means the - * result might not be the first item in the original `coll` (in terms of order) - * that passes the test. - - * If order within the original `coll` is important, then look at - * [`detectSeries`]{@link module:Collections.detectSeries}. - * - * @name detect - * @static - * @memberOf module:Collections - * @method - * @alias find - * @category Collections - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. - * The iteratee must complete with a boolean value as its result. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the `iteratee` functions have finished. - * Result will be the first item in the array that passes the truth test - * (iteratee) or the value `undefined` if none passed. Invoked with - * (err, result). - * @example - * - * async.detect(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // result now equals the first file in the list that exists - * }); - */ -var detect = doParallel(_createTester(identity, _findGetResult)); - -/** - * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a - * time. - * - * @name detectLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.detect]{@link module:Collections.detect} - * @alias findLimit - * @category Collections - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. - * The iteratee must complete with a boolean value as its result. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the `iteratee` functions have finished. - * Result will be the first item in the array that passes the truth test - * (iteratee) or the value `undefined` if none passed. Invoked with - * (err, result). - */ -var detectLimit = doParallelLimit(_createTester(identity, _findGetResult)); - -/** - * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. - * - * @name detectSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.detect]{@link module:Collections.detect} - * @alias findSeries - * @category Collections - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. - * The iteratee must complete with a boolean value as its result. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the `iteratee` functions have finished. - * Result will be the first item in the array that passes the truth test - * (iteratee) or the value `undefined` if none passed. Invoked with - * (err, result). - */ -var detectSeries = doLimit(detectLimit, 1); - -function consoleFunc(name) { - return function (fn/*, ...args*/) { - var args = slice(arguments, 1); - args.push(function (err/*, ...args*/) { - var args = slice(arguments, 1); - if (typeof console === 'object') { - if (err) { - if (console.error) { - console.error(err); - } - } else if (console[name]) { - arrayEach(args, function (x) { - console[name](x); - }); - } - } - }); - wrapAsync(fn).apply(null, args); - }; -} - -/** - * Logs the result of an [`async` function]{@link AsyncFunction} to the - * `console` using `console.dir` to display the properties of the resulting object. - * Only works in Node.js or in browsers that support `console.dir` and - * `console.error` (such as FF and Chrome). - * If multiple arguments are returned from the async function, - * `console.dir` is called on each argument in order. - * - * @name dir - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} function - The function you want to eventually apply - * all arguments to. - * @param {...*} arguments... - Any number of arguments to apply to the function. - * @example - * - * // in a module - * var hello = function(name, callback) { - * setTimeout(function() { - * callback(null, {hello: name}); - * }, 1000); - * }; - * - * // in the node repl - * node> async.dir(hello, 'world'); - * {hello: 'world'} - */ -var dir = consoleFunc('dir'); - -/** - * The post-check version of [`during`]{@link module:ControlFlow.during}. To reflect the difference in - * the order of operations, the arguments `test` and `fn` are switched. - * - * Also a version of [`doWhilst`]{@link module:ControlFlow.doWhilst} with asynchronous `test` function. - * @name doDuring - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.during]{@link module:ControlFlow.during} - * @category Control Flow - * @param {AsyncFunction} fn - An async function which is called each time - * `test` passes. Invoked with (callback). - * @param {AsyncFunction} test - asynchronous truth test to perform before each - * execution of `fn`. Invoked with (...args, callback), where `...args` are the - * non-error args from the previous callback of `fn`. - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `fn` has stopped. `callback` - * will be passed an error if one occurred, otherwise `null`. - */ -function doDuring(fn, test, callback) { - callback = onlyOnce(callback || noop); - var _fn = wrapAsync(fn); - var _test = wrapAsync(test); - - function next(err/*, ...args*/) { - if (err) return callback(err); - var args = slice(arguments, 1); - args.push(check); - _test.apply(this, args); - } - - function check(err, truth) { - if (err) return callback(err); - if (!truth) return callback(null); - _fn(next); - } - - check(null, true); - -} - -/** - * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in - * the order of operations, the arguments `test` and `iteratee` are switched. - * - * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. - * - * @name doWhilst - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.whilst]{@link module:ControlFlow.whilst} - * @category Control Flow - * @param {AsyncFunction} iteratee - A function which is called each time `test` - * passes. Invoked with (callback). - * @param {Function} test - synchronous truth test to perform after each - * execution of `iteratee`. Invoked with any non-error callback results of - * `iteratee`. - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `iteratee` has stopped. - * `callback` will be passed an error and any arguments passed to the final - * `iteratee`'s callback. Invoked with (err, [results]); - */ -function doWhilst(iteratee, test, callback) { - callback = onlyOnce(callback || noop); - var _iteratee = wrapAsync(iteratee); - var next = function(err/*, ...args*/) { - if (err) return callback(err); - var args = slice(arguments, 1); - if (test.apply(this, args)) return _iteratee(next); - callback.apply(null, [null].concat(args)); - }; - _iteratee(next); -} - -/** - * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the - * argument ordering differs from `until`. - * - * @name doUntil - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.doWhilst]{@link module:ControlFlow.doWhilst} - * @category Control Flow - * @param {AsyncFunction} iteratee - An async function which is called each time - * `test` fails. Invoked with (callback). - * @param {Function} test - synchronous truth test to perform after each - * execution of `iteratee`. Invoked with any non-error callback results of - * `iteratee`. - * @param {Function} [callback] - A callback which is called after the test - * function has passed and repeated execution of `iteratee` has stopped. `callback` - * will be passed an error and any arguments passed to the final `iteratee`'s - * callback. Invoked with (err, [results]); - */ -function doUntil(iteratee, test, callback) { - doWhilst(iteratee, function() { - return !test.apply(this, arguments); - }, callback); -} - -/** - * Like [`whilst`]{@link module:ControlFlow.whilst}, except the `test` is an asynchronous function that - * is passed a callback in the form of `function (err, truth)`. If error is - * passed to `test` or `fn`, the main callback is immediately called with the - * value of the error. - * - * @name during - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.whilst]{@link module:ControlFlow.whilst} - * @category Control Flow - * @param {AsyncFunction} test - asynchronous truth test to perform before each - * execution of `fn`. Invoked with (callback). - * @param {AsyncFunction} fn - An async function which is called each time - * `test` passes. Invoked with (callback). - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `fn` has stopped. `callback` - * will be passed an error, if one occurred, otherwise `null`. - * @example - * - * var count = 0; - * - * async.during( - * function (callback) { - * return callback(null, count < 5); - * }, - * function (callback) { - * count++; - * setTimeout(callback, 1000); - * }, - * function (err) { - * // 5 seconds have passed - * } - * ); - */ -function during(test, fn, callback) { - callback = onlyOnce(callback || noop); - var _fn = wrapAsync(fn); - var _test = wrapAsync(test); - - function next(err) { - if (err) return callback(err); - _test(check); - } - - function check(err, truth) { - if (err) return callback(err); - if (!truth) return callback(null); - _fn(next); - } - - _test(check); -} - -function _withoutIndex(iteratee) { - return function (value, index, callback) { - return iteratee(value, callback); - }; -} - -/** - * Applies the function `iteratee` to each item in `coll`, in parallel. - * The `iteratee` is called with an item from the list, and a callback for when - * it has finished. If the `iteratee` passes an error to its `callback`, the - * main `callback` (for the `each` function) is immediately called with the - * error. - * - * Note, that since this function applies `iteratee` to each item in parallel, - * there is no guarantee that the iteratee functions will complete in order. - * - * @name each - * @static - * @memberOf module:Collections - * @method - * @alias forEach - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to - * each item in `coll`. Invoked with (item, callback). - * The array index is not passed to the iteratee. - * If you need the index, use `eachOf`. - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - * @example - * - * // assuming openFiles is an array of file names and saveFile is a function - * // to save the modified contents of that file: - * - * async.each(openFiles, saveFile, function(err){ - * // if any of the saves produced an error, err would equal that error - * }); - * - * // assuming openFiles is an array of file names - * async.each(openFiles, function(file, callback) { - * - * // Perform operation on file here. - * console.log('Processing file ' + file); - * - * if( file.length > 32 ) { - * console.log('This file name is too long'); - * callback('File name too long'); - * } else { - * // Do work to process file here - * console.log('File processed'); - * callback(); - * } - * }, function(err) { - * // if any of the file processing produced an error, err would equal that error - * if( err ) { - * // One of the iterations produced an error. - * // All processing will now stop. - * console.log('A file failed to process'); - * } else { - * console.log('All files have been processed successfully'); - * } - * }); - */ -function eachLimit(coll, iteratee, callback) { - eachOf(coll, _withoutIndex(wrapAsync(iteratee)), callback); -} - -/** - * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. - * - * @name eachLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.each]{@link module:Collections.each} - * @alias forEachLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The array index is not passed to the iteratee. - * If you need the index, use `eachOfLimit`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - */ -function eachLimit$1(coll, limit, iteratee, callback) { - _eachOfLimit(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback); -} - -/** - * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. - * - * @name eachSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.each]{@link module:Collections.each} - * @alias forEachSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each - * item in `coll`. - * The array index is not passed to the iteratee. - * If you need the index, use `eachOfSeries`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - */ -var eachSeries = doLimit(eachLimit$1, 1); - -/** - * Wrap an async function and ensure it calls its callback on a later tick of - * the event loop. If the function already calls its callback on a next tick, - * no extra deferral is added. This is useful for preventing stack overflows - * (`RangeError: Maximum call stack size exceeded`) and generally keeping - * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) - * contained. ES2017 `async` functions are returned as-is -- they are immune - * to Zalgo's corrupting influences, as they always resolve on a later tick. - * - * @name ensureAsync - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} fn - an async function, one that expects a node-style - * callback as its last argument. - * @returns {AsyncFunction} Returns a wrapped function with the exact same call - * signature as the function passed in. - * @example - * - * function sometimesAsync(arg, callback) { - * if (cache[arg]) { - * return callback(null, cache[arg]); // this would be synchronous!! - * } else { - * doSomeIO(arg, callback); // this IO would be asynchronous - * } - * } - * - * // this has a risk of stack overflows if many results are cached in a row - * async.mapSeries(args, sometimesAsync, done); - * - * // this will defer sometimesAsync's callback if necessary, - * // preventing stack overflows - * async.mapSeries(args, async.ensureAsync(sometimesAsync), done); - */ -function ensureAsync(fn) { - if (isAsync(fn)) return fn; - return initialParams(function (args, callback) { - var sync = true; - args.push(function () { - var innerArgs = arguments; - if (sync) { - setImmediate$1(function () { - callback.apply(null, innerArgs); - }); - } else { - callback.apply(null, innerArgs); - } - }); - fn.apply(this, args); - sync = false; - }); -} - -function notId(v) { - return !v; -} - -/** - * Returns `true` if every element in `coll` satisfies an async test. If any - * iteratee call returns `false`, the main `callback` is immediately called. - * - * @name every - * @static - * @memberOf module:Collections - * @method - * @alias all - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in parallel. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - * @example - * - * async.every(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // if result is true then every file exists - * }); - */ -var every = doParallel(_createTester(notId, notId)); - -/** - * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. - * - * @name everyLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.every]{@link module:Collections.every} - * @alias allLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in parallel. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - */ -var everyLimit = doParallelLimit(_createTester(notId, notId)); - -/** - * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. - * - * @name everySeries - * @static - * @memberOf module:Collections - * @method - * @see [async.every]{@link module:Collections.every} - * @alias allSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in series. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - */ -var everySeries = doLimit(everyLimit, 1); - -/** - * The base implementation of `_.property` without support for deep paths. - * - * @private - * @param {string} key The key of the property to get. - * @returns {Function} Returns the new accessor function. - */ -function baseProperty(key) { - return function(object) { - return object == null ? undefined : object[key]; - }; -} - -function filterArray(eachfn, arr, iteratee, callback) { - var truthValues = new Array(arr.length); - eachfn(arr, function (x, index, callback) { - iteratee(x, function (err, v) { - truthValues[index] = !!v; - callback(err); - }); - }, function (err) { - if (err) return callback(err); - var results = []; - for (var i = 0; i < arr.length; i++) { - if (truthValues[i]) results.push(arr[i]); - } - callback(null, results); - }); -} - -function filterGeneric(eachfn, coll, iteratee, callback) { - var results = []; - eachfn(coll, function (x, index, callback) { - iteratee(x, function (err, v) { - if (err) { - callback(err); - } else { - if (v) { - results.push({index: index, value: x}); - } - callback(); - } - }); - }, function (err) { - if (err) { - callback(err); - } else { - callback(null, arrayMap(results.sort(function (a, b) { - return a.index - b.index; - }), baseProperty('value'))); - } - }); -} - -function _filter(eachfn, coll, iteratee, callback) { - var filter = isArrayLike(coll) ? filterArray : filterGeneric; - filter(eachfn, coll, wrapAsync(iteratee), callback || noop); -} - -/** - * Returns a new array of all the values in `coll` which pass an async truth - * test. This operation is performed in parallel, but the results array will be - * in the same order as the original. - * - * @name filter - * @static - * @memberOf module:Collections - * @method - * @alias select - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - A truth test to apply to each item in `coll`. - * The `iteratee` is passed a `callback(err, truthValue)`, which must be called - * with a boolean argument once it has completed. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - * @example - * - * async.filter(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, results) { - * // results now equals an array of the existing files - * }); - */ -var filter = doParallel(_filter); - -/** - * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a - * time. - * - * @name filterLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.filter]{@link module:Collections.filter} - * @alias selectLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {Function} iteratee - A truth test to apply to each item in `coll`. - * The `iteratee` is passed a `callback(err, truthValue)`, which must be called - * with a boolean argument once it has completed. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - */ -var filterLimit = doParallelLimit(_filter); - -/** - * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. - * - * @name filterSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.filter]{@link module:Collections.filter} - * @alias selectSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - A truth test to apply to each item in `coll`. - * The `iteratee` is passed a `callback(err, truthValue)`, which must be called - * with a boolean argument once it has completed. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results) - */ -var filterSeries = doLimit(filterLimit, 1); - -/** - * Calls the asynchronous function `fn` with a callback parameter that allows it - * to call itself again, in series, indefinitely. - - * If an error is passed to the callback then `errback` is called with the - * error, and execution stops, otherwise it will never be called. - * - * @name forever - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {AsyncFunction} fn - an async function to call repeatedly. - * Invoked with (next). - * @param {Function} [errback] - when `fn` passes an error to it's callback, - * this function will be called, and execution stops. Invoked with (err). - * @example - * - * async.forever( - * function(next) { - * // next is suitable for passing to things that need a callback(err [, whatever]); - * // it will result in this function being called again. - * }, - * function(err) { - * // if next is called with a value in its first parameter, it will appear - * // in here as 'err', and execution will stop. - * } - * ); - */ -function forever(fn, errback) { - var done = onlyOnce(errback || noop); - var task = wrapAsync(ensureAsync(fn)); - - function next(err) { - if (err) return done(err); - task(next); - } - next(); -} - -/** - * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time. - * - * @name groupByLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.groupBy]{@link module:Collections.groupBy} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a `key` to group the value under. - * Invoked with (value, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Result is an `Object` whoses - * properties are arrays of values which returned the corresponding key. - */ -var groupByLimit = function(coll, limit, iteratee, callback) { - callback = callback || noop; - var _iteratee = wrapAsync(iteratee); - mapLimit(coll, limit, function(val, callback) { - _iteratee(val, function(err, key) { - if (err) return callback(err); - return callback(null, {key: key, val: val}); - }); - }, function(err, mapResults) { - var result = {}; - // from MDN, handle object having an `hasOwnProperty` prop - var hasOwnProperty = Object.prototype.hasOwnProperty; - - for (var i = 0; i < mapResults.length; i++) { - if (mapResults[i]) { - var key = mapResults[i].key; - var val = mapResults[i].val; - - if (hasOwnProperty.call(result, key)) { - result[key].push(val); - } else { - result[key] = [val]; - } - } - } - - return callback(err, result); - }); -}; - -/** - * Returns a new object, where each value corresponds to an array of items, from - * `coll`, that returned the corresponding key. That is, the keys of the object - * correspond to the values passed to the `iteratee` callback. - * - * Note: Since this function applies the `iteratee` to each item in parallel, - * there is no guarantee that the `iteratee` functions will complete in order. - * However, the values for each key in the `result` will be in the same order as - * the original `coll`. For Objects, the values will roughly be in the order of - * the original Objects' keys (but this can vary across JavaScript engines). - * - * @name groupBy - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a `key` to group the value under. - * Invoked with (value, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Result is an `Object` whoses - * properties are arrays of values which returned the corresponding key. - * @example - * - * async.groupBy(['userId1', 'userId2', 'userId3'], function(userId, callback) { - * db.findById(userId, function(err, user) { - * if (err) return callback(err); - * return callback(null, user.age); - * }); - * }, function(err, result) { - * // result is object containing the userIds grouped by age - * // e.g. { 30: ['userId1', 'userId3'], 42: ['userId2']}; - * }); - */ -var groupBy = doLimit(groupByLimit, Infinity); - -/** - * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time. - * - * @name groupBySeries - * @static - * @memberOf module:Collections - * @method - * @see [async.groupBy]{@link module:Collections.groupBy} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a `key` to group the value under. - * Invoked with (value, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Result is an `Object` whoses - * properties are arrays of values which returned the corresponding key. - */ -var groupBySeries = doLimit(groupByLimit, 1); - -/** - * Logs the result of an `async` function to the `console`. Only works in - * Node.js or in browsers that support `console.log` and `console.error` (such - * as FF and Chrome). If multiple arguments are returned from the async - * function, `console.log` is called on each argument in order. - * - * @name log - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} function - The function you want to eventually apply - * all arguments to. - * @param {...*} arguments... - Any number of arguments to apply to the function. - * @example - * - * // in a module - * var hello = function(name, callback) { - * setTimeout(function() { - * callback(null, 'hello ' + name); - * }, 1000); - * }; - * - * // in the node repl - * node> async.log(hello, 'world'); - * 'hello world' - */ -var log = consoleFunc('log'); - -/** - * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a - * time. - * - * @name mapValuesLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.mapValues]{@link module:Collections.mapValues} - * @category Collection - * @param {Object} obj - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - A function to apply to each value and key - * in `coll`. - * The iteratee should complete with the transformed value as its result. - * Invoked with (value, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. `result` is a new object consisting - * of each key from `obj`, with each transformed value on the right-hand side. - * Invoked with (err, result). - */ -function mapValuesLimit(obj, limit, iteratee, callback) { - callback = once(callback || noop); - var newObj = {}; - var _iteratee = wrapAsync(iteratee); - eachOfLimit(obj, limit, function(val, key, next) { - _iteratee(val, key, function (err, result) { - if (err) return next(err); - newObj[key] = result; - next(); - }); - }, function (err) { - callback(err, newObj); - }); -} - -/** - * A relative of [`map`]{@link module:Collections.map}, designed for use with objects. - * - * Produces a new Object by mapping each value of `obj` through the `iteratee` - * function. The `iteratee` is called each `value` and `key` from `obj` and a - * callback for when it has finished processing. Each of these callbacks takes - * two arguments: an `error`, and the transformed item from `obj`. If `iteratee` - * passes an error to its callback, the main `callback` (for the `mapValues` - * function) is immediately called with the error. - * - * Note, the order of the keys in the result is not guaranteed. The keys will - * be roughly in the order they complete, (but this is very engine-specific) - * - * @name mapValues - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Object} obj - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each value and key - * in `coll`. - * The iteratee should complete with the transformed value as its result. - * Invoked with (value, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. `result` is a new object consisting - * of each key from `obj`, with each transformed value on the right-hand side. - * Invoked with (err, result). - * @example - * - * async.mapValues({ - * f1: 'file1', - * f2: 'file2', - * f3: 'file3' - * }, function (file, key, callback) { - * fs.stat(file, callback); - * }, function(err, result) { - * // result is now a map of stats for each file, e.g. - * // { - * // f1: [stats for file1], - * // f2: [stats for file2], - * // f3: [stats for file3] - * // } - * }); - */ - -var mapValues = doLimit(mapValuesLimit, Infinity); - -/** - * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time. - * - * @name mapValuesSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.mapValues]{@link module:Collections.mapValues} - * @category Collection - * @param {Object} obj - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each value and key - * in `coll`. - * The iteratee should complete with the transformed value as its result. - * Invoked with (value, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. `result` is a new object consisting - * of each key from `obj`, with each transformed value on the right-hand side. - * Invoked with (err, result). - */ -var mapValuesSeries = doLimit(mapValuesLimit, 1); - -function has(obj, key) { - return key in obj; -} - -/** - * Caches the results of an async function. When creating a hash to store - * function results against, the callback is omitted from the hash and an - * optional hash function can be used. - * - * If no hash function is specified, the first argument is used as a hash key, - * which may work reasonably if it is a string or a data type that converts to a - * distinct string. Note that objects and arrays will not behave reasonably. - * Neither will cases where the other arguments are significant. In such cases, - * specify your own hash function. - * - * The cache of results is exposed as the `memo` property of the function - * returned by `memoize`. - * - * @name memoize - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} fn - The async function to proxy and cache results from. - * @param {Function} hasher - An optional function for generating a custom hash - * for storing results. It has all the arguments applied to it apart from the - * callback, and must be synchronous. - * @returns {AsyncFunction} a memoized version of `fn` - * @example - * - * var slow_fn = function(name, callback) { - * // do something - * callback(null, result); - * }; - * var fn = async.memoize(slow_fn); - * - * // fn can now be used as if it were slow_fn - * fn('some name', function() { - * // callback - * }); - */ -function memoize(fn, hasher) { - var memo = Object.create(null); - var queues = Object.create(null); - hasher = hasher || identity; - var _fn = wrapAsync(fn); - var memoized = initialParams(function memoized(args, callback) { - var key = hasher.apply(null, args); - if (has(memo, key)) { - setImmediate$1(function() { - callback.apply(null, memo[key]); - }); - } else if (has(queues, key)) { - queues[key].push(callback); - } else { - queues[key] = [callback]; - _fn.apply(null, args.concat(function(/*args*/) { - var args = slice(arguments); - memo[key] = args; - var q = queues[key]; - delete queues[key]; - for (var i = 0, l = q.length; i < l; i++) { - q[i].apply(null, args); - } - })); - } - }); - memoized.memo = memo; - memoized.unmemoized = fn; - return memoized; -} - -/** - * Calls `callback` on a later loop around the event loop. In Node.js this just - * calls `process.nextTicl`. In the browser it will use `setImmediate` if - * available, otherwise `setTimeout(callback, 0)`, which means other higher - * priority events may precede the execution of `callback`. - * - * This is used internally for browser-compatibility purposes. - * - * @name nextTick - * @static - * @memberOf module:Utils - * @method - * @see [async.setImmediate]{@link module:Utils.setImmediate} - * @category Util - * @param {Function} callback - The function to call on a later loop around - * the event loop. Invoked with (args...). - * @param {...*} args... - any number of additional arguments to pass to the - * callback on the next tick. - * @example - * - * var call_order = []; - * async.nextTick(function() { - * call_order.push('two'); - * // call_order now equals ['one','two'] - * }); - * call_order.push('one'); - * - * async.setImmediate(function (a, b, c) { - * // a, b, and c equal 1, 2, and 3 - * }, 1, 2, 3); - */ -var _defer$1; - -if (hasNextTick) { - _defer$1 = process.nextTick; -} else if (hasSetImmediate) { - _defer$1 = setImmediate; -} else { - _defer$1 = fallback; -} - -var nextTick = wrap(_defer$1); - -function _parallel(eachfn, tasks, callback) { - callback = callback || noop; - var results = isArrayLike(tasks) ? [] : {}; - - eachfn(tasks, function (task, key, callback) { - wrapAsync(task)(function (err, result) { - if (arguments.length > 2) { - result = slice(arguments, 1); - } - results[key] = result; - callback(err); - }); - }, function (err) { - callback(err, results); - }); -} - -/** - * Run the `tasks` collection of functions in parallel, without waiting until - * the previous function has completed. If any of the functions pass an error to - * its callback, the main `callback` is immediately called with the value of the - * error. Once the `tasks` have completed, the results are passed to the final - * `callback` as an array. - * - * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about - * parallel execution of code. If your tasks do not use any timers or perform - * any I/O, they will actually be executed in series. Any synchronous setup - * sections for each task will happen one after the other. JavaScript remains - * single-threaded. - * - * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the - * execution of other tasks when a task fails. - * - * It is also possible to use an object instead of an array. Each property will - * be run as a function and the results will be passed to the final `callback` - * as an object instead of an array. This can be a more readable way of handling - * results from {@link async.parallel}. - * - * @name parallel - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|Object} tasks - A collection of - * [async functions]{@link AsyncFunction} to run. - * Each async function can complete with any number of optional `result` values. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed successfully. This function gets a results array - * (or object) containing all the result arguments passed to the task callbacks. - * Invoked with (err, results). - * - * @example - * async.parallel([ - * function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * setTimeout(function() { - * callback(null, 'two'); - * }, 100); - * } - * ], - * // optional callback - * function(err, results) { - * // the results array will equal ['one','two'] even though - * // the second function had a shorter timeout. - * }); - * - * // an example using an object instead of an array - * async.parallel({ - * one: function(callback) { - * setTimeout(function() { - * callback(null, 1); - * }, 200); - * }, - * two: function(callback) { - * setTimeout(function() { - * callback(null, 2); - * }, 100); - * } - * }, function(err, results) { - * // results is now equals to: {one: 1, two: 2} - * }); - */ -function parallelLimit(tasks, callback) { - _parallel(eachOf, tasks, callback); -} - -/** - * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a - * time. - * - * @name parallelLimit - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.parallel]{@link module:ControlFlow.parallel} - * @category Control Flow - * @param {Array|Iterable|Object} tasks - A collection of - * [async functions]{@link AsyncFunction} to run. - * Each async function can complete with any number of optional `result` values. - * @param {number} limit - The maximum number of async operations at a time. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed successfully. This function gets a results array - * (or object) containing all the result arguments passed to the task callbacks. - * Invoked with (err, results). - */ -function parallelLimit$1(tasks, limit, callback) { - _parallel(_eachOfLimit(limit), tasks, callback); -} - -/** - * A queue of tasks for the worker function to complete. - * @typedef {Object} QueueObject - * @memberOf module:ControlFlow - * @property {Function} length - a function returning the number of items - * waiting to be processed. Invoke with `queue.length()`. - * @property {boolean} started - a boolean indicating whether or not any - * items have been pushed and processed by the queue. - * @property {Function} running - a function returning the number of items - * currently being processed. Invoke with `queue.running()`. - * @property {Function} workersList - a function returning the array of items - * currently being processed. Invoke with `queue.workersList()`. - * @property {Function} idle - a function returning false if there are items - * waiting or being processed, or true if not. Invoke with `queue.idle()`. - * @property {number} concurrency - an integer for determining how many `worker` - * functions should be run in parallel. This property can be changed after a - * `queue` is created to alter the concurrency on-the-fly. - * @property {Function} push - add a new task to the `queue`. Calls `callback` - * once the `worker` has finished processing the task. Instead of a single task, - * a `tasks` array can be submitted. The respective callback is used for every - * task in the list. Invoke with `queue.push(task, [callback])`, - * @property {Function} unshift - add a new task to the front of the `queue`. - * Invoke with `queue.unshift(task, [callback])`. - * @property {Function} remove - remove items from the queue that match a test - * function. The test function will be passed an object with a `data` property, - * and a `priority` property, if this is a - * [priorityQueue]{@link module:ControlFlow.priorityQueue} object. - * Invoked with `queue.remove(testFn)`, where `testFn` is of the form - * `function ({data, priority}) {}` and returns a Boolean. - * @property {Function} saturated - a callback that is called when the number of - * running workers hits the `concurrency` limit, and further tasks will be - * queued. - * @property {Function} unsaturated - a callback that is called when the number - * of running workers is less than the `concurrency` & `buffer` limits, and - * further tasks will not be queued. - * @property {number} buffer - A minimum threshold buffer in order to say that - * the `queue` is `unsaturated`. - * @property {Function} empty - a callback that is called when the last item - * from the `queue` is given to a `worker`. - * @property {Function} drain - a callback that is called when the last item - * from the `queue` has returned from the `worker`. - * @property {Function} error - a callback that is called when a task errors. - * Has the signature `function(error, task)`. - * @property {boolean} paused - a boolean for determining whether the queue is - * in a paused state. - * @property {Function} pause - a function that pauses the processing of tasks - * until `resume()` is called. Invoke with `queue.pause()`. - * @property {Function} resume - a function that resumes the processing of - * queued tasks when the queue is paused. Invoke with `queue.resume()`. - * @property {Function} kill - a function that removes the `drain` callback and - * empties remaining tasks from the queue forcing it to go idle. No more tasks - * should be pushed to the queue after calling this function. Invoke with `queue.kill()`. - */ - -/** - * Creates a `queue` object with the specified `concurrency`. Tasks added to the - * `queue` are processed in parallel (up to the `concurrency` limit). If all - * `worker`s are in progress, the task is queued until one becomes available. - * Once a `worker` completes a `task`, that `task`'s callback is called. - * - * @name queue - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {AsyncFunction} worker - An async function for processing a queued task. - * If you want to handle errors from an individual task, pass a callback to - * `q.push()`. Invoked with (task, callback). - * @param {number} [concurrency=1] - An `integer` for determining how many - * `worker` functions should be run in parallel. If omitted, the concurrency - * defaults to `1`. If the concurrency is `0`, an error is thrown. - * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can - * attached as certain properties to listen for specific events during the - * lifecycle of the queue. - * @example - * - * // create a queue object with concurrency 2 - * var q = async.queue(function(task, callback) { - * console.log('hello ' + task.name); - * callback(); - * }, 2); - * - * // assign a callback - * q.drain = function() { - * console.log('all items have been processed'); - * }; - * - * // add some items to the queue - * q.push({name: 'foo'}, function(err) { - * console.log('finished processing foo'); - * }); - * q.push({name: 'bar'}, function (err) { - * console.log('finished processing bar'); - * }); - * - * // add some items to the queue (batch-wise) - * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) { - * console.log('finished processing item'); - * }); - * - * // add some items to the front of the queue - * q.unshift({name: 'bar'}, function (err) { - * console.log('finished processing bar'); - * }); - */ -var queue$1 = function (worker, concurrency) { - var _worker = wrapAsync(worker); - return queue(function (items, cb) { - _worker(items[0], cb); - }, concurrency, 1); -}; - -/** - * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and - * completed in ascending priority order. - * - * @name priorityQueue - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.queue]{@link module:ControlFlow.queue} - * @category Control Flow - * @param {AsyncFunction} worker - An async function for processing a queued task. - * If you want to handle errors from an individual task, pass a callback to - * `q.push()`. - * Invoked with (task, callback). - * @param {number} concurrency - An `integer` for determining how many `worker` - * functions should be run in parallel. If omitted, the concurrency defaults to - * `1`. If the concurrency is `0`, an error is thrown. - * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are two - * differences between `queue` and `priorityQueue` objects: - * * `push(task, priority, [callback])` - `priority` should be a number. If an - * array of `tasks` is given, all tasks will be assigned the same priority. - * * The `unshift` method was removed. - */ -var priorityQueue = function(worker, concurrency) { - // Start with a normal queue - var q = queue$1(worker, concurrency); - - // Override push to accept second parameter representing priority - q.push = function(data, priority, callback) { - if (callback == null) callback = noop; - if (typeof callback !== 'function') { - throw new Error('task callback must be a function'); - } - q.started = true; - if (!isArray(data)) { - data = [data]; - } - if (data.length === 0) { - // call drain immediately if there are no tasks - return setImmediate$1(function() { - q.drain(); - }); - } - - priority = priority || 0; - var nextNode = q._tasks.head; - while (nextNode && priority >= nextNode.priority) { - nextNode = nextNode.next; - } - - for (var i = 0, l = data.length; i < l; i++) { - var item = { - data: data[i], - priority: priority, - callback: callback - }; - - if (nextNode) { - q._tasks.insertBefore(nextNode, item); - } else { - q._tasks.push(item); - } - } - setImmediate$1(q.process); - }; - - // Remove unshift function - delete q.unshift; - - return q; -}; - -/** - * Runs the `tasks` array of functions in parallel, without waiting until the - * previous function has completed. Once any of the `tasks` complete or pass an - * error to its callback, the main `callback` is immediately called. It's - * equivalent to `Promise.race()`. - * - * @name race - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction} - * to run. Each function can complete with an optional `result` value. - * @param {Function} callback - A callback to run once any of the functions have - * completed. This function gets an error or result from the first function that - * completed. Invoked with (err, result). - * @returns undefined - * @example - * - * async.race([ - * function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * setTimeout(function() { - * callback(null, 'two'); - * }, 100); - * } - * ], - * // main callback - * function(err, result) { - * // the result will be equal to 'two' as it finishes earlier - * }); - */ -function race(tasks, callback) { - callback = once(callback || noop); - if (!isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions')); - if (!tasks.length) return callback(); - for (var i = 0, l = tasks.length; i < l; i++) { - wrapAsync(tasks[i])(callback); - } -} - -/** - * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. - * - * @name reduceRight - * @static - * @memberOf module:Collections - * @method - * @see [async.reduce]{@link module:Collections.reduce} - * @alias foldr - * @category Collection - * @param {Array} array - A collection to iterate over. - * @param {*} memo - The initial state of the reduction. - * @param {AsyncFunction} iteratee - A function applied to each item in the - * array to produce the next step in the reduction. - * The `iteratee` should complete with the next state of the reduction. - * If the iteratee complete with an error, the reduction is stopped and the - * main `callback` is immediately called with the error. - * Invoked with (memo, item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result is the reduced value. Invoked with - * (err, result). - */ -function reduceRight (array, memo, iteratee, callback) { - var reversed = slice(array).reverse(); - reduce(reversed, memo, iteratee, callback); -} - -/** - * Wraps the async function in another function that always completes with a - * result object, even when it errors. - * - * The result object has either the property `error` or `value`. - * - * @name reflect - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} fn - The async function you want to wrap - * @returns {Function} - A function that always passes null to it's callback as - * the error. The second argument to the callback will be an `object` with - * either an `error` or a `value` property. - * @example - * - * async.parallel([ - * async.reflect(function(callback) { - * // do some stuff ... - * callback(null, 'one'); - * }), - * async.reflect(function(callback) { - * // do some more stuff but error ... - * callback('bad stuff happened'); - * }), - * async.reflect(function(callback) { - * // do some more stuff ... - * callback(null, 'two'); - * }) - * ], - * // optional callback - * function(err, results) { - * // values - * // results[0].value = 'one' - * // results[1].error = 'bad stuff happened' - * // results[2].value = 'two' - * }); - */ -function reflect(fn) { - var _fn = wrapAsync(fn); - return initialParams(function reflectOn(args, reflectCallback) { - args.push(function callback(error, cbArg) { - if (error) { - reflectCallback(null, { error: error }); - } else { - var value; - if (arguments.length <= 2) { - value = cbArg; - } else { - value = slice(arguments, 1); - } - reflectCallback(null, { value: value }); - } - }); - - return _fn.apply(this, args); - }); -} - -/** - * A helper function that wraps an array or an object of functions with `reflect`. - * - * @name reflectAll - * @static - * @memberOf module:Utils - * @method - * @see [async.reflect]{@link module:Utils.reflect} - * @category Util - * @param {Array|Object|Iterable} tasks - The collection of - * [async functions]{@link AsyncFunction} to wrap in `async.reflect`. - * @returns {Array} Returns an array of async functions, each wrapped in - * `async.reflect` - * @example - * - * let tasks = [ - * function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * // do some more stuff but error ... - * callback(new Error('bad stuff happened')); - * }, - * function(callback) { - * setTimeout(function() { - * callback(null, 'two'); - * }, 100); - * } - * ]; - * - * async.parallel(async.reflectAll(tasks), - * // optional callback - * function(err, results) { - * // values - * // results[0].value = 'one' - * // results[1].error = Error('bad stuff happened') - * // results[2].value = 'two' - * }); - * - * // an example using an object instead of an array - * let tasks = { - * one: function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * two: function(callback) { - * callback('two'); - * }, - * three: function(callback) { - * setTimeout(function() { - * callback(null, 'three'); - * }, 100); - * } - * }; - * - * async.parallel(async.reflectAll(tasks), - * // optional callback - * function(err, results) { - * // values - * // results.one.value = 'one' - * // results.two.error = 'two' - * // results.three.value = 'three' - * }); - */ -function reflectAll(tasks) { - var results; - if (isArray(tasks)) { - results = arrayMap(tasks, reflect); - } else { - results = {}; - baseForOwn(tasks, function(task, key) { - results[key] = reflect.call(this, task); - }); - } - return results; -} - -function reject$1(eachfn, arr, iteratee, callback) { - _filter(eachfn, arr, function(value, cb) { - iteratee(value, function(err, v) { - cb(err, !v); - }); - }, callback); -} - -/** - * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test. - * - * @name reject - * @static - * @memberOf module:Collections - * @method - * @see [async.filter]{@link module:Collections.filter} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - An async truth test to apply to each item in - * `coll`. - * The should complete with a boolean value as its `result`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - * @example - * - * async.reject(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, results) { - * // results now equals an array of missing files - * createFiles(results); - * }); - */ -var reject = doParallel(reject$1); - -/** - * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a - * time. - * - * @name rejectLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.reject]{@link module:Collections.reject} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {Function} iteratee - An async truth test to apply to each item in - * `coll`. - * The should complete with a boolean value as its `result`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - */ -var rejectLimit = doParallelLimit(reject$1); - -/** - * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time. - * - * @name rejectSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.reject]{@link module:Collections.reject} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - An async truth test to apply to each item in - * `coll`. - * The should complete with a boolean value as its `result`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - */ -var rejectSeries = doLimit(rejectLimit, 1); - -/** - * Creates a function that returns `value`. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Util - * @param {*} value The value to return from the new function. - * @returns {Function} Returns the new constant function. - * @example - * - * var objects = _.times(2, _.constant({ 'a': 1 })); - * - * console.log(objects); - * // => [{ 'a': 1 }, { 'a': 1 }] - * - * console.log(objects[0] === objects[1]); - * // => true - */ -function constant$1(value) { - return function() { - return value; - }; -} - -/** - * Attempts to get a successful response from `task` no more than `times` times - * before returning an error. If the task is successful, the `callback` will be - * passed the result of the successful task. If all attempts fail, the callback - * will be passed the error and result (if any) of the final attempt. - * - * @name retry - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @see [async.retryable]{@link module:ControlFlow.retryable} - * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an - * object with `times` and `interval` or a number. - * * `times` - The number of attempts to make before giving up. The default - * is `5`. - * * `interval` - The time to wait between retries, in milliseconds. The - * default is `0`. The interval may also be specified as a function of the - * retry count (see example). - * * `errorFilter` - An optional synchronous function that is invoked on - * erroneous result. If it returns `true` the retry attempts will continue; - * if the function returns `false` the retry flow is aborted with the current - * attempt's error and result being returned to the final callback. - * Invoked with (err). - * * If `opts` is a number, the number specifies the number of times to retry, - * with the default interval of `0`. - * @param {AsyncFunction} task - An async function to retry. - * Invoked with (callback). - * @param {Function} [callback] - An optional callback which is called when the - * task has succeeded, or after the final failed attempt. It receives the `err` - * and `result` arguments of the last attempt at completing the `task`. Invoked - * with (err, results). - * - * @example - * - * // The `retry` function can be used as a stand-alone control flow by passing - * // a callback, as shown below: - * - * // try calling apiMethod 3 times - * async.retry(3, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod 3 times, waiting 200 ms between each retry - * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod 10 times with exponential backoff - * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds) - * async.retry({ - * times: 10, - * interval: function(retryCount) { - * return 50 * Math.pow(2, retryCount); - * } - * }, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod the default 5 times no delay between each retry - * async.retry(apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod only when error condition satisfies, all other - * // errors will abort the retry control flow and return to final callback - * async.retry({ - * errorFilter: function(err) { - * return err.message === 'Temporary error'; // only retry on a specific error - * } - * }, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // to retry individual methods that are not as reliable within other - * // control flow functions, use the `retryable` wrapper: - * async.auto({ - * users: api.getUsers.bind(api), - * payments: async.retryable(3, api.getPayments.bind(api)) - * }, function(err, results) { - * // do something with the results - * }); - * - */ -function retry(opts, task, callback) { - var DEFAULT_TIMES = 5; - var DEFAULT_INTERVAL = 0; - - var options = { - times: DEFAULT_TIMES, - intervalFunc: constant$1(DEFAULT_INTERVAL) - }; - - function parseTimes(acc, t) { - if (typeof t === 'object') { - acc.times = +t.times || DEFAULT_TIMES; - - acc.intervalFunc = typeof t.interval === 'function' ? - t.interval : - constant$1(+t.interval || DEFAULT_INTERVAL); - - acc.errorFilter = t.errorFilter; - } else if (typeof t === 'number' || typeof t === 'string') { - acc.times = +t || DEFAULT_TIMES; - } else { - throw new Error("Invalid arguments for async.retry"); - } - } - - if (arguments.length < 3 && typeof opts === 'function') { - callback = task || noop; - task = opts; - } else { - parseTimes(options, opts); - callback = callback || noop; - } - - if (typeof task !== 'function') { - throw new Error("Invalid arguments for async.retry"); - } - - var _task = wrapAsync(task); - - var attempt = 1; - function retryAttempt() { - _task(function(err) { - if (err && attempt++ < options.times && - (typeof options.errorFilter != 'function' || - options.errorFilter(err))) { - setTimeout(retryAttempt, options.intervalFunc(attempt)); - } else { - callback.apply(null, arguments); - } - }); - } - - retryAttempt(); -} - -/** - * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method - * wraps a task and makes it retryable, rather than immediately calling it - * with retries. - * - * @name retryable - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.retry]{@link module:ControlFlow.retry} - * @category Control Flow - * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional - * options, exactly the same as from `retry` - * @param {AsyncFunction} task - the asynchronous function to wrap. - * This function will be passed any arguments passed to the returned wrapper. - * Invoked with (...args, callback). - * @returns {AsyncFunction} The wrapped function, which when invoked, will - * retry on an error, based on the parameters specified in `opts`. - * This function will accept the same parameters as `task`. - * @example - * - * async.auto({ - * dep1: async.retryable(3, getFromFlakyService), - * process: ["dep1", async.retryable(3, function (results, cb) { - * maybeProcessData(results.dep1, cb); - * })] - * }, callback); - */ -var retryable = function (opts, task) { - if (!task) { - task = opts; - opts = null; - } - var _task = wrapAsync(task); - return initialParams(function (args, callback) { - function taskFn(cb) { - _task.apply(null, args.concat(cb)); - } - - if (opts) retry(opts, taskFn, callback); - else retry(taskFn, callback); - - }); -}; - -/** - * Run the functions in the `tasks` collection in series, each one running once - * the previous function has completed. If any functions in the series pass an - * error to its callback, no more functions are run, and `callback` is - * immediately called with the value of the error. Otherwise, `callback` - * receives an array of results when `tasks` have completed. - * - * It is also possible to use an object instead of an array. Each property will - * be run as a function, and the results will be passed to the final `callback` - * as an object instead of an array. This can be a more readable way of handling - * results from {@link async.series}. - * - * **Note** that while many implementations preserve the order of object - * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) - * explicitly states that - * - * > The mechanics and order of enumerating the properties is not specified. - * - * So if you rely on the order in which your series of functions are executed, - * and want this to work on all platforms, consider using an array. - * - * @name series - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|Object} tasks - A collection containing - * [async functions]{@link AsyncFunction} to run in series. - * Each function can complete with any number of optional `result` values. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed. This function gets a results array (or object) - * containing all the result arguments passed to the `task` callbacks. Invoked - * with (err, result). - * @example - * async.series([ - * function(callback) { - * // do some stuff ... - * callback(null, 'one'); - * }, - * function(callback) { - * // do some more stuff ... - * callback(null, 'two'); - * } - * ], - * // optional callback - * function(err, results) { - * // results is now equal to ['one', 'two'] - * }); - * - * async.series({ - * one: function(callback) { - * setTimeout(function() { - * callback(null, 1); - * }, 200); - * }, - * two: function(callback){ - * setTimeout(function() { - * callback(null, 2); - * }, 100); - * } - * }, function(err, results) { - * // results is now equal to: {one: 1, two: 2} - * }); - */ -function series(tasks, callback) { - _parallel(eachOfSeries, tasks, callback); -} - -/** - * Returns `true` if at least one element in the `coll` satisfies an async test. - * If any iteratee call returns `true`, the main `callback` is immediately - * called. - * - * @name some - * @static - * @memberOf module:Collections - * @method - * @alias any - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in parallel. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - * @example - * - * async.some(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // if result is true then at least one of the files exists - * }); - */ -var some = doParallel(_createTester(Boolean, identity)); - -/** - * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. - * - * @name someLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.some]{@link module:Collections.some} - * @alias anyLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in parallel. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - */ -var someLimit = doParallelLimit(_createTester(Boolean, identity)); - -/** - * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. - * - * @name someSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.some]{@link module:Collections.some} - * @alias anySeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in series. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - */ -var someSeries = doLimit(someLimit, 1); - -/** - * Sorts a list by the results of running each `coll` value through an async - * `iteratee`. - * - * @name sortBy - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a value to use as the sort criteria as - * its `result`. - * Invoked with (item, callback). - * @param {Function} callback - A callback which is called after all the - * `iteratee` functions have finished, or an error occurs. Results is the items - * from the original `coll` sorted by the values returned by the `iteratee` - * calls. Invoked with (err, results). - * @example - * - * async.sortBy(['file1','file2','file3'], function(file, callback) { - * fs.stat(file, function(err, stats) { - * callback(err, stats.mtime); - * }); - * }, function(err, results) { - * // results is now the original array of files sorted by - * // modified date - * }); - * - * // By modifying the callback parameter the - * // sorting order can be influenced: - * - * // ascending order - * async.sortBy([1,9,3,5], function(x, callback) { - * callback(null, x); - * }, function(err,result) { - * // result callback - * }); - * - * // descending order - * async.sortBy([1,9,3,5], function(x, callback) { - * callback(null, x*-1); //<- x*-1 instead of x, turns the order around - * }, function(err,result) { - * // result callback - * }); - */ -function sortBy (coll, iteratee, callback) { - var _iteratee = wrapAsync(iteratee); - map(coll, function (x, callback) { - _iteratee(x, function (err, criteria) { - if (err) return callback(err); - callback(null, {value: x, criteria: criteria}); - }); - }, function (err, results) { - if (err) return callback(err); - callback(null, arrayMap(results.sort(comparator), baseProperty('value'))); - }); - - function comparator(left, right) { - var a = left.criteria, b = right.criteria; - return a < b ? -1 : a > b ? 1 : 0; - } -} - -/** - * Sets a time limit on an asynchronous function. If the function does not call - * its callback within the specified milliseconds, it will be called with a - * timeout error. The code property for the error object will be `'ETIMEDOUT'`. - * - * @name timeout - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} asyncFn - The async function to limit in time. - * @param {number} milliseconds - The specified time limit. - * @param {*} [info] - Any variable you want attached (`string`, `object`, etc) - * to timeout Error for more information.. - * @returns {AsyncFunction} Returns a wrapped function that can be used with any - * of the control flow functions. - * Invoke this function with the same parameters as you would `asyncFunc`. - * @example - * - * function myFunction(foo, callback) { - * doAsyncTask(foo, function(err, data) { - * // handle errors - * if (err) return callback(err); - * - * // do some stuff ... - * - * // return processed data - * return callback(null, data); - * }); - * } - * - * var wrapped = async.timeout(myFunction, 1000); - * - * // call `wrapped` as you would `myFunction` - * wrapped({ bar: 'bar' }, function(err, data) { - * // if `myFunction` takes < 1000 ms to execute, `err` - * // and `data` will have their expected values - * - * // else `err` will be an Error with the code 'ETIMEDOUT' - * }); - */ -function timeout(asyncFn, milliseconds, info) { - var fn = wrapAsync(asyncFn); - - return initialParams(function (args, callback) { - var timedOut = false; - var timer; - - function timeoutCallback() { - var name = asyncFn.name || 'anonymous'; - var error = new Error('Callback function "' + name + '" timed out.'); - error.code = 'ETIMEDOUT'; - if (info) { - error.info = info; - } - timedOut = true; - callback(error); - } - - args.push(function () { - if (!timedOut) { - callback.apply(null, arguments); - clearTimeout(timer); - } - }); - - // setup timer and call original function - timer = setTimeout(timeoutCallback, milliseconds); - fn.apply(null, args); - }); -} - -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeCeil = Math.ceil; -var nativeMax = Math.max; - -/** - * The base implementation of `_.range` and `_.rangeRight` which doesn't - * coerce arguments. - * - * @private - * @param {number} start The start of the range. - * @param {number} end The end of the range. - * @param {number} step The value to increment or decrement by. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Array} Returns the range of numbers. - */ -function baseRange(start, end, step, fromRight) { - var index = -1, - length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), - result = Array(length); - - while (length--) { - result[fromRight ? length : ++index] = start; - start += step; - } - return result; -} - -/** - * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a - * time. - * - * @name timesLimit - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.times]{@link module:ControlFlow.times} - * @category Control Flow - * @param {number} count - The number of times to run the function. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - The async function to call `n` times. - * Invoked with the iteration index and a callback: (n, next). - * @param {Function} callback - see [async.map]{@link module:Collections.map}. - */ -function timeLimit(count, limit, iteratee, callback) { - var _iteratee = wrapAsync(iteratee); - mapLimit(baseRange(0, count, 1), limit, _iteratee, callback); -} - -/** - * Calls the `iteratee` function `n` times, and accumulates results in the same - * manner you would use with [map]{@link module:Collections.map}. - * - * @name times - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.map]{@link module:Collections.map} - * @category Control Flow - * @param {number} n - The number of times to run the function. - * @param {AsyncFunction} iteratee - The async function to call `n` times. - * Invoked with the iteration index and a callback: (n, next). - * @param {Function} callback - see {@link module:Collections.map}. - * @example - * - * // Pretend this is some complicated async factory - * var createUser = function(id, callback) { - * callback(null, { - * id: 'user' + id - * }); - * }; - * - * // generate 5 users - * async.times(5, function(n, next) { - * createUser(n, function(err, user) { - * next(err, user); - * }); - * }, function(err, users) { - * // we should now have 5 users - * }); - */ -var times = doLimit(timeLimit, Infinity); - -/** - * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time. - * - * @name timesSeries - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.times]{@link module:ControlFlow.times} - * @category Control Flow - * @param {number} n - The number of times to run the function. - * @param {AsyncFunction} iteratee - The async function to call `n` times. - * Invoked with the iteration index and a callback: (n, next). - * @param {Function} callback - see {@link module:Collections.map}. - */ -var timesSeries = doLimit(timeLimit, 1); - -/** - * A relative of `reduce`. Takes an Object or Array, and iterates over each - * element in series, each step potentially mutating an `accumulator` value. - * The type of the accumulator defaults to the type of collection passed in. - * - * @name transform - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {*} [accumulator] - The initial state of the transform. If omitted, - * it will default to an empty Object or Array, depending on the type of `coll` - * @param {AsyncFunction} iteratee - A function applied to each item in the - * collection that potentially modifies the accumulator. - * Invoked with (accumulator, item, key, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result is the transformed accumulator. - * Invoked with (err, result). - * @example - * - * async.transform([1,2,3], function(acc, item, index, callback) { - * // pointless async: - * process.nextTick(function() { - * acc.push(item * 2) - * callback(null) - * }); - * }, function(err, result) { - * // result is now equal to [2, 4, 6] - * }); - * - * @example - * - * async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) { - * setImmediate(function () { - * obj[key] = val * 2; - * callback(); - * }) - * }, function (err, result) { - * // result is equal to {a: 2, b: 4, c: 6} - * }) - */ -function transform (coll, accumulator, iteratee, callback) { - if (arguments.length <= 3) { - callback = iteratee; - iteratee = accumulator; - accumulator = isArray(coll) ? [] : {}; - } - callback = once(callback || noop); - var _iteratee = wrapAsync(iteratee); - - eachOf(coll, function(v, k, cb) { - _iteratee(accumulator, v, k, cb); - }, function(err) { - callback(err, accumulator); - }); -} - -/** - * It runs each task in series but stops whenever any of the functions were - * successful. If one of the tasks were successful, the `callback` will be - * passed the result of the successful task. If all tasks fail, the callback - * will be passed the error and result (if any) of the final attempt. - * - * @name tryEach - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|Object} tasks - A collection containing functions to - * run, each function is passed a `callback(err, result)` it must call on - * completion with an error `err` (which can be `null`) and an optional `result` - * value. - * @param {Function} [callback] - An optional callback which is called when one - * of the tasks has succeeded, or all have failed. It receives the `err` and - * `result` arguments of the last attempt at completing the `task`. Invoked with - * (err, results). - * @example - * async.tryEach([ - * function getDataFromFirstWebsite(callback) { - * // Try getting the data from the first website - * callback(err, data); - * }, - * function getDataFromSecondWebsite(callback) { - * // First website failed, - * // Try getting the data from the backup website - * callback(err, data); - * } - * ], - * // optional callback - * function(err, results) { - * Now do something with the data. - * }); - * - */ -function tryEach(tasks, callback) { - var error = null; - var result; - callback = callback || noop; - eachSeries(tasks, function(task, callback) { - wrapAsync(task)(function (err, res/*, ...args*/) { - if (arguments.length > 2) { - result = slice(arguments, 1); - } else { - result = res; - } - error = err; - callback(!err); - }); - }, function () { - callback(error, result); - }); -} - -/** - * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, - * unmemoized form. Handy for testing. - * - * @name unmemoize - * @static - * @memberOf module:Utils - * @method - * @see [async.memoize]{@link module:Utils.memoize} - * @category Util - * @param {AsyncFunction} fn - the memoized function - * @returns {AsyncFunction} a function that calls the original unmemoized function - */ -function unmemoize(fn) { - return function () { - return (fn.unmemoized || fn).apply(null, arguments); - }; -} - -/** - * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when - * stopped, or an error occurs. - * - * @name whilst - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Function} test - synchronous truth test to perform before each - * execution of `iteratee`. Invoked with (). - * @param {AsyncFunction} iteratee - An async function which is called each time - * `test` passes. Invoked with (callback). - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `iteratee` has stopped. `callback` - * will be passed an error and any arguments passed to the final `iteratee`'s - * callback. Invoked with (err, [results]); - * @returns undefined - * @example - * - * var count = 0; - * async.whilst( - * function() { return count < 5; }, - * function(callback) { - * count++; - * setTimeout(function() { - * callback(null, count); - * }, 1000); - * }, - * function (err, n) { - * // 5 seconds have passed, n = 5 - * } - * ); - */ -function whilst(test, iteratee, callback) { - callback = onlyOnce(callback || noop); - var _iteratee = wrapAsync(iteratee); - if (!test()) return callback(null); - var next = function(err/*, ...args*/) { - if (err) return callback(err); - if (test()) return _iteratee(next); - var args = slice(arguments, 1); - callback.apply(null, [null].concat(args)); - }; - _iteratee(next); -} - -/** - * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when - * stopped, or an error occurs. `callback` will be passed an error and any - * arguments passed to the final `iteratee`'s callback. - * - * The inverse of [whilst]{@link module:ControlFlow.whilst}. - * - * @name until - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.whilst]{@link module:ControlFlow.whilst} - * @category Control Flow - * @param {Function} test - synchronous truth test to perform before each - * execution of `iteratee`. Invoked with (). - * @param {AsyncFunction} iteratee - An async function which is called each time - * `test` fails. Invoked with (callback). - * @param {Function} [callback] - A callback which is called after the test - * function has passed and repeated execution of `iteratee` has stopped. `callback` - * will be passed an error and any arguments passed to the final `iteratee`'s - * callback. Invoked with (err, [results]); - */ -function until(test, iteratee, callback) { - whilst(function() { - return !test.apply(this, arguments); - }, iteratee, callback); -} - -/** - * Runs the `tasks` array of functions in series, each passing their results to - * the next in the array. However, if any of the `tasks` pass an error to their - * own callback, the next function is not executed, and the main `callback` is - * immediately called with the error. - * - * @name waterfall - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} - * to run. - * Each function should complete with any number of `result` values. - * The `result` values will be passed as arguments, in order, to the next task. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed. This will be passed the results of the last task's - * callback. Invoked with (err, [results]). - * @returns undefined - * @example - * - * async.waterfall([ - * function(callback) { - * callback(null, 'one', 'two'); - * }, - * function(arg1, arg2, callback) { - * // arg1 now equals 'one' and arg2 now equals 'two' - * callback(null, 'three'); - * }, - * function(arg1, callback) { - * // arg1 now equals 'three' - * callback(null, 'done'); - * } - * ], function (err, result) { - * // result now equals 'done' - * }); - * - * // Or, with named functions: - * async.waterfall([ - * myFirstFunction, - * mySecondFunction, - * myLastFunction, - * ], function (err, result) { - * // result now equals 'done' - * }); - * function myFirstFunction(callback) { - * callback(null, 'one', 'two'); - * } - * function mySecondFunction(arg1, arg2, callback) { - * // arg1 now equals 'one' and arg2 now equals 'two' - * callback(null, 'three'); - * } - * function myLastFunction(arg1, callback) { - * // arg1 now equals 'three' - * callback(null, 'done'); - * } - */ -var waterfall = function(tasks, callback) { - callback = once(callback || noop); - if (!isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); - if (!tasks.length) return callback(); - var taskIndex = 0; - - function nextTask(args) { - var task = wrapAsync(tasks[taskIndex++]); - args.push(onlyOnce(next)); - task.apply(null, args); - } - - function next(err/*, ...args*/) { - if (err || taskIndex === tasks.length) { - return callback.apply(null, arguments); - } - nextTask(slice(arguments, 1)); - } - - nextTask([]); -}; - -/** - * An "async function" in the context of Async is an asynchronous function with - * a variable number of parameters, with the final parameter being a callback. - * (`function (arg1, arg2, ..., callback) {}`) - * The final callback is of the form `callback(err, results...)`, which must be - * called once the function is completed. The callback should be called with a - * Error as its first argument to signal that an error occurred. - * Otherwise, if no error occurred, it should be called with `null` as the first - * argument, and any additional `result` arguments that may apply, to signal - * successful completion. - * The callback must be called exactly once, ideally on a later tick of the - * JavaScript event loop. - * - * This type of function is also referred to as a "Node-style async function", - * or a "continuation passing-style function" (CPS). Most of the methods of this - * library are themselves CPS/Node-style async functions, or functions that - * return CPS/Node-style async functions. - * - * Wherever we accept a Node-style async function, we also directly accept an - * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. - * In this case, the `async` function will not be passed a final callback - * argument, and any thrown error will be used as the `err` argument of the - * implicit callback, and the return value will be used as the `result` value. - * (i.e. a `rejected` of the returned Promise becomes the `err` callback - * argument, and a `resolved` value becomes the `result`.) - * - * Note, due to JavaScript limitations, we can only detect native `async` - * functions and not transpilied implementations. - * Your environment must have `async`/`await` support for this to work. - * (e.g. Node > v7.6, or a recent version of a modern browser). - * If you are using `async` functions through a transpiler (e.g. Babel), you - * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, - * because the `async function` will be compiled to an ordinary function that - * returns a promise. - * - * @typedef {Function} AsyncFunction - * @static - */ - -/** - * Async is a utility module which provides straight-forward, powerful functions - * for working with asynchronous JavaScript. Although originally designed for - * use with [Node.js](http://nodejs.org) and installable via - * `npm install --save async`, it can also be used directly in the browser. - * @module async - * @see AsyncFunction - */ - - -/** - * A collection of `async` functions for manipulating collections, such as - * arrays and objects. - * @module Collections - */ - -/** - * A collection of `async` functions for controlling the flow through a script. - * @module ControlFlow - */ - -/** - * A collection of `async` utility functions. - * @module Utils - */ - -var index = { - apply: apply, - applyEach: applyEach, - applyEachSeries: applyEachSeries, - asyncify: asyncify, - auto: auto, - autoInject: autoInject, - cargo: cargo, - compose: compose, - concat: concat, - concatLimit: concatLimit, - concatSeries: concatSeries, - constant: constant, - detect: detect, - detectLimit: detectLimit, - detectSeries: detectSeries, - dir: dir, - doDuring: doDuring, - doUntil: doUntil, - doWhilst: doWhilst, - during: during, - each: eachLimit, - eachLimit: eachLimit$1, - eachOf: eachOf, - eachOfLimit: eachOfLimit, - eachOfSeries: eachOfSeries, - eachSeries: eachSeries, - ensureAsync: ensureAsync, - every: every, - everyLimit: everyLimit, - everySeries: everySeries, - filter: filter, - filterLimit: filterLimit, - filterSeries: filterSeries, - forever: forever, - groupBy: groupBy, - groupByLimit: groupByLimit, - groupBySeries: groupBySeries, - log: log, - map: map, - mapLimit: mapLimit, - mapSeries: mapSeries, - mapValues: mapValues, - mapValuesLimit: mapValuesLimit, - mapValuesSeries: mapValuesSeries, - memoize: memoize, - nextTick: nextTick, - parallel: parallelLimit, - parallelLimit: parallelLimit$1, - priorityQueue: priorityQueue, - queue: queue$1, - race: race, - reduce: reduce, - reduceRight: reduceRight, - reflect: reflect, - reflectAll: reflectAll, - reject: reject, - rejectLimit: rejectLimit, - rejectSeries: rejectSeries, - retry: retry, - retryable: retryable, - seq: seq, - series: series, - setImmediate: setImmediate$1, - some: some, - someLimit: someLimit, - someSeries: someSeries, - sortBy: sortBy, - timeout: timeout, - times: times, - timesLimit: timeLimit, - timesSeries: timesSeries, - transform: transform, - tryEach: tryEach, - unmemoize: unmemoize, - until: until, - waterfall: waterfall, - whilst: whilst, - - // aliases - all: every, - allLimit: everyLimit, - allSeries: everySeries, - any: some, - anyLimit: someLimit, - anySeries: someSeries, - find: detect, - findLimit: detectLimit, - findSeries: detectSeries, - forEach: eachLimit, - forEachSeries: eachSeries, - forEachLimit: eachLimit$1, - forEachOf: eachOf, - forEachOfSeries: eachOfSeries, - forEachOfLimit: eachOfLimit, - inject: reduce, - foldl: reduce, - foldr: reduceRight, - select: filter, - selectLimit: filterLimit, - selectSeries: filterSeries, - wrapSync: asyncify -}; - -exports['default'] = index; -exports.apply = apply; -exports.applyEach = applyEach; -exports.applyEachSeries = applyEachSeries; -exports.asyncify = asyncify; -exports.auto = auto; -exports.autoInject = autoInject; -exports.cargo = cargo; -exports.compose = compose; -exports.concat = concat; -exports.concatLimit = concatLimit; -exports.concatSeries = concatSeries; -exports.constant = constant; -exports.detect = detect; -exports.detectLimit = detectLimit; -exports.detectSeries = detectSeries; -exports.dir = dir; -exports.doDuring = doDuring; -exports.doUntil = doUntil; -exports.doWhilst = doWhilst; -exports.during = during; -exports.each = eachLimit; -exports.eachLimit = eachLimit$1; -exports.eachOf = eachOf; -exports.eachOfLimit = eachOfLimit; -exports.eachOfSeries = eachOfSeries; -exports.eachSeries = eachSeries; -exports.ensureAsync = ensureAsync; -exports.every = every; -exports.everyLimit = everyLimit; -exports.everySeries = everySeries; -exports.filter = filter; -exports.filterLimit = filterLimit; -exports.filterSeries = filterSeries; -exports.forever = forever; -exports.groupBy = groupBy; -exports.groupByLimit = groupByLimit; -exports.groupBySeries = groupBySeries; -exports.log = log; -exports.map = map; -exports.mapLimit = mapLimit; -exports.mapSeries = mapSeries; -exports.mapValues = mapValues; -exports.mapValuesLimit = mapValuesLimit; -exports.mapValuesSeries = mapValuesSeries; -exports.memoize = memoize; -exports.nextTick = nextTick; -exports.parallel = parallelLimit; -exports.parallelLimit = parallelLimit$1; -exports.priorityQueue = priorityQueue; -exports.queue = queue$1; -exports.race = race; -exports.reduce = reduce; -exports.reduceRight = reduceRight; -exports.reflect = reflect; -exports.reflectAll = reflectAll; -exports.reject = reject; -exports.rejectLimit = rejectLimit; -exports.rejectSeries = rejectSeries; -exports.retry = retry; -exports.retryable = retryable; -exports.seq = seq; -exports.series = series; -exports.setImmediate = setImmediate$1; -exports.some = some; -exports.someLimit = someLimit; -exports.someSeries = someSeries; -exports.sortBy = sortBy; -exports.timeout = timeout; -exports.times = times; -exports.timesLimit = timeLimit; -exports.timesSeries = timesSeries; -exports.transform = transform; -exports.tryEach = tryEach; -exports.unmemoize = unmemoize; -exports.until = until; -exports.waterfall = waterfall; -exports.whilst = whilst; -exports.all = every; -exports.allLimit = everyLimit; -exports.allSeries = everySeries; -exports.any = some; -exports.anyLimit = someLimit; -exports.anySeries = someSeries; -exports.find = detect; -exports.findLimit = detectLimit; -exports.findSeries = detectSeries; -exports.forEach = eachLimit; -exports.forEachSeries = eachSeries; -exports.forEachLimit = eachLimit$1; -exports.forEachOf = eachOf; -exports.forEachOfSeries = eachOfSeries; -exports.forEachOfLimit = eachOfLimit; -exports.inject = reduce; -exports.foldl = reduce; -exports.foldr = reduceRight; -exports.select = filter; -exports.selectLimit = filterLimit; -exports.selectSeries = filterSeries; -exports.wrapSync = asyncify; - -Object.defineProperty(exports, '__esModule', { value: true }); - -}))); diff --git a/node_modules/webpack/node_modules/async/dist/async.min.js b/node_modules/webpack/node_modules/async/dist/async.min.js deleted file mode 100644 index 7b8e87c14..000000000 --- a/node_modules/webpack/node_modules/async/dist/async.min.js +++ /dev/null @@ -1,2 +0,0 @@ -!function(n,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(n.async=n.async||{})}(this,function(n){"use strict";function t(n,t){t|=0;for(var e=Math.max(n.length-t,0),r=Array(e),u=0;u<e;u++)r[u]=n[t+u];return r}function e(n){var t=typeof n;return null!=n&&("object"==t||"function"==t)}function r(n){setTimeout(n,0)}function u(n){return function(e){var r=t(arguments,1);n(function(){e.apply(null,r)})}}function i(n){return ct(function(t,r){var u;try{u=n.apply(this,t)}catch(n){return r(n)}e(u)&&"function"==typeof u.then?u.then(function(n){o(r,null,n)},function(n){o(r,n.message?n:new Error(n))}):r(null,u)})}function o(n,t,e){try{n(t,e)}catch(n){lt(c,n)}}function c(n){throw n}function f(n){return st&&"AsyncFunction"===n[Symbol.toStringTag]}function a(n){return f(n)?i(n):n}function l(n){return function(e){var r=t(arguments,1),u=ct(function(t,r){var u=this;return n(e,function(n,e){a(n).apply(u,t.concat(e))},r)});return r.length?u.apply(this,r):u}}function s(n){var t=mt.call(n,bt),e=n[bt];try{n[bt]=void 0;var r=!0}catch(n){}var u=gt.call(n);return r&&(t?n[bt]=e:delete n[bt]),u}function p(n){return St.call(n)}function h(n){return null==n?void 0===n?Lt:kt:Ot&&Ot in Object(n)?s(n):p(n)}function y(n){if(!e(n))return!1;var t=h(n);return t==xt||t==Et||t==wt||t==At}function v(n){return"number"==typeof n&&n>-1&&n%1==0&&n<=Tt}function d(n){return null!=n&&v(n.length)&&!y(n)}function m(){}function g(n){return function(){if(null!==n){var t=n;n=null,t.apply(this,arguments)}}}function b(n,t){for(var e=-1,r=Array(n);++e<n;)r[e]=t(e);return r}function j(n){return null!=n&&"object"==typeof n}function S(n){return j(n)&&h(n)==_t}function k(){return!1}function L(n,t){return t=null==t?Nt:t,!!t&&("number"==typeof n||Qt.test(n))&&n>-1&&n%1==0&&n<t}function O(n){return j(n)&&v(n.length)&&!!me[h(n)]}function w(n){return function(t){return n(t)}}function x(n,t){var e=Vt(n),r=!e&&Pt(n),u=!e&&!r&&Wt(n),i=!e&&!r&&!u&&Oe(n),o=e||r||u||i,c=o?b(n.length,String):[],f=c.length;for(var a in n)!t&&!xe.call(n,a)||o&&("length"==a||u&&("offset"==a||"parent"==a)||i&&("buffer"==a||"byteLength"==a||"byteOffset"==a)||L(a,f))||c.push(a);return c}function E(n){var t=n&&n.constructor,e="function"==typeof t&&t.prototype||Ee;return n===e}function A(n,t){return function(e){return n(t(e))}}function T(n){if(!E(n))return Ae(n);var t=[];for(var e in Object(n))Be.call(n,e)&&"constructor"!=e&&t.push(e);return t}function B(n){return d(n)?x(n):T(n)}function F(n){var t=-1,e=n.length;return function(){return++t<e?{value:n[t],key:t}:null}}function I(n){var t=-1;return function(){var e=n.next();return e.done?null:(t++,{value:e.value,key:t})}}function _(n){var t=B(n),e=-1,r=t.length;return function(){var u=t[++e];return e<r?{value:n[u],key:u}:null}}function M(n){if(d(n))return F(n);var t=It(n);return t?I(t):_(n)}function U(n){return function(){if(null===n)throw new Error("Callback was already called.");var t=n;n=null,t.apply(this,arguments)}}function z(n){return function(t,e,r){function u(n,t){if(f-=1,n)c=!0,r(n);else{if(t===Bt||c&&f<=0)return c=!0,r(null);i()}}function i(){for(;f<n&&!c;){var t=o();if(null===t)return c=!0,void(f<=0&&r(null));f+=1,e(t.value,t.key,U(u))}}if(r=g(r||m),n<=0||!t)return r(null);var o=M(t),c=!1,f=0;i()}}function P(n,t,e,r){z(t)(n,a(e),r)}function V(n,t){return function(e,r,u){return n(e,t,r,u)}}function q(n,t,e){function r(n,t){n?e(n):++i!==o&&t!==Bt||e(null)}e=g(e||m);var u=0,i=0,o=n.length;for(0===o&&e(null);u<o;u++)t(n[u],u,U(r))}function D(n){return function(t,e,r){return n(Ie,t,a(e),r)}}function R(n,t,e,r){r=r||m,t=t||[];var u=[],i=0,o=a(e);n(t,function(n,t,e){var r=i++;o(n,function(n,t){u[r]=t,e(n)})},function(n){r(n,u)})}function C(n){return function(t,e,r,u){return n(z(e),t,a(r),u)}}function $(n,t){for(var e=-1,r=null==n?0:n.length;++e<r&&t(n[e],e,n)!==!1;);return n}function W(n){return function(t,e,r){for(var u=-1,i=Object(t),o=r(t),c=o.length;c--;){var f=o[n?c:++u];if(e(i[f],f,i)===!1)break}return t}}function N(n,t){return n&&Ve(n,t,B)}function Q(n,t,e,r){for(var u=n.length,i=e+(r?1:-1);r?i--:++i<u;)if(t(n[i],i,n))return i;return-1}function G(n){return n!==n}function H(n,t,e){for(var r=e-1,u=n.length;++r<u;)if(n[r]===t)return r;return-1}function J(n,t,e){return t===t?H(n,t,e):Q(n,G,e)}function K(n,t){for(var e=-1,r=null==n?0:n.length,u=Array(r);++e<r;)u[e]=t(n[e],e,n);return u}function X(n){return"symbol"==typeof n||j(n)&&h(n)==De}function Y(n){if("string"==typeof n)return n;if(Vt(n))return K(n,Y)+"";if(X(n))return $e?$e.call(n):"";var t=n+"";return"0"==t&&1/n==-Re?"-0":t}function Z(n,t,e){var r=-1,u=n.length;t<0&&(t=-t>u?0:u+t),e=e>u?u:e,e<0&&(e+=u),u=t>e?0:e-t>>>0,t>>>=0;for(var i=Array(u);++r<u;)i[r]=n[r+t];return i}function nn(n,t,e){var r=n.length;return e=void 0===e?r:e,!t&&e>=r?n:Z(n,t,e)}function tn(n,t){for(var e=n.length;e--&&J(t,n[e],0)>-1;);return e}function en(n,t){for(var e=-1,r=n.length;++e<r&&J(t,n[e],0)>-1;);return e}function rn(n){return n.split("")}function un(n){return Xe.test(n)}function on(n){return n.match(mr)||[]}function cn(n){return un(n)?on(n):rn(n)}function fn(n){return null==n?"":Y(n)}function an(n,t,e){if(n=fn(n),n&&(e||void 0===t))return n.replace(gr,"");if(!n||!(t=Y(t)))return n;var r=cn(n),u=cn(t),i=en(r,u),o=tn(r,u)+1;return nn(r,i,o).join("")}function ln(n){return n=n.toString().replace(kr,""),n=n.match(br)[2].replace(" ",""),n=n?n.split(jr):[],n=n.map(function(n){return an(n.replace(Sr,""))})}function sn(n,t){var e={};N(n,function(n,t){function r(t,e){var r=K(u,function(n){return t[n]});r.push(e),a(n).apply(null,r)}var u,i=f(n),o=!i&&1===n.length||i&&0===n.length;if(Vt(n))u=n.slice(0,-1),n=n[n.length-1],e[t]=u.concat(u.length>0?r:n);else if(o)e[t]=n;else{if(u=ln(n),0===n.length&&!i&&0===u.length)throw new Error("autoInject task functions require explicit parameters.");i||u.pop(),e[t]=u.concat(r)}}),qe(e,t)}function pn(){this.head=this.tail=null,this.length=0}function hn(n,t){n.length=1,n.head=n.tail=t}function yn(n,t,e){function r(n,t,e){if(null!=e&&"function"!=typeof e)throw new Error("task callback must be a function");if(s.started=!0,Vt(n)||(n=[n]),0===n.length&&s.idle())return lt(function(){s.drain()});for(var r=0,u=n.length;r<u;r++){var i={data:n[r],callback:e||m};t?s._tasks.unshift(i):s._tasks.push(i)}f||(f=!0,lt(function(){f=!1,s.process()}))}function u(n){return function(t){o-=1;for(var e=0,r=n.length;e<r;e++){var u=n[e],i=J(c,u,0);0===i?c.shift():i>0&&c.splice(i,1),u.callback.apply(u,arguments),null!=t&&s.error(t,u.data)}o<=s.concurrency-s.buffer&&s.unsaturated(),s.idle()&&s.drain(),s.process()}}if(null==t)t=1;else if(0===t)throw new Error("Concurrency must not be zero");var i=a(n),o=0,c=[],f=!1,l=!1,s={_tasks:new pn,concurrency:t,payload:e,saturated:m,unsaturated:m,buffer:t/4,empty:m,drain:m,error:m,started:!1,paused:!1,push:function(n,t){r(n,!1,t)},kill:function(){s.drain=m,s._tasks.empty()},unshift:function(n,t){r(n,!0,t)},remove:function(n){s._tasks.remove(n)},process:function(){if(!l){for(l=!0;!s.paused&&o<s.concurrency&&s._tasks.length;){var n=[],t=[],e=s._tasks.length;s.payload&&(e=Math.min(e,s.payload));for(var r=0;r<e;r++){var f=s._tasks.shift();n.push(f),c.push(f),t.push(f.data)}o+=1,0===s._tasks.length&&s.empty(),o===s.concurrency&&s.saturated();var a=U(u(n));i(t,a)}l=!1}},length:function(){return s._tasks.length},running:function(){return o},workersList:function(){return c},idle:function(){return s._tasks.length+o===0},pause:function(){s.paused=!0},resume:function(){s.paused!==!1&&(s.paused=!1,lt(s.process))}};return s}function vn(n,t){return yn(n,1,t)}function dn(n,t,e,r){r=g(r||m);var u=a(e);Or(n,function(n,e,r){u(t,n,function(n,e){t=e,r(n)})},function(n){r(n,t)})}function mn(){var n=K(arguments,a);return function(){var e=t(arguments),r=this,u=e[e.length-1];"function"==typeof u?e.pop():u=m,dn(n,e,function(n,e,u){e.apply(r,n.concat(function(n){var e=t(arguments,1);u(n,e)}))},function(n,t){u.apply(r,[n].concat(t))})}}function gn(n){return n}function bn(n,t){return function(e,r,u,i){i=i||m;var o,c=!1;e(r,function(e,r,i){u(e,function(r,u){r?i(r):n(u)&&!o?(c=!0,o=t(!0,e),i(null,Bt)):i()})},function(n){n?i(n):i(null,c?o:t(!1))})}}function jn(n,t){return t}function Sn(n){return function(e){var r=t(arguments,1);r.push(function(e){var r=t(arguments,1);"object"==typeof console&&(e?console.error&&console.error(e):console[n]&&$(r,function(t){console[n](t)}))}),a(e).apply(null,r)}}function kn(n,e,r){function u(n){if(n)return r(n);var e=t(arguments,1);e.push(i),c.apply(this,e)}function i(n,t){return n?r(n):t?void o(u):r(null)}r=U(r||m);var o=a(n),c=a(e);i(null,!0)}function Ln(n,e,r){r=U(r||m);var u=a(n),i=function(n){if(n)return r(n);var o=t(arguments,1);return e.apply(this,o)?u(i):void r.apply(null,[null].concat(o))};u(i)}function On(n,t,e){Ln(n,function(){return!t.apply(this,arguments)},e)}function wn(n,t,e){function r(n){return n?e(n):void o(u)}function u(n,t){return n?e(n):t?void i(r):e(null)}e=U(e||m);var i=a(t),o=a(n);o(u)}function xn(n){return function(t,e,r){return n(t,r)}}function En(n,t,e){Ie(n,xn(a(t)),e)}function An(n,t,e,r){z(t)(n,xn(a(e)),r)}function Tn(n){return f(n)?n:ct(function(t,e){var r=!0;t.push(function(){var n=arguments;r?lt(function(){e.apply(null,n)}):e.apply(null,n)}),n.apply(this,t),r=!1})}function Bn(n){return!n}function Fn(n){return function(t){return null==t?void 0:t[n]}}function In(n,t,e,r){var u=new Array(t.length);n(t,function(n,t,r){e(n,function(n,e){u[t]=!!e,r(n)})},function(n){if(n)return r(n);for(var e=[],i=0;i<t.length;i++)u[i]&&e.push(t[i]);r(null,e)})}function _n(n,t,e,r){var u=[];n(t,function(n,t,r){e(n,function(e,i){e?r(e):(i&&u.push({index:t,value:n}),r())})},function(n){n?r(n):r(null,K(u.sort(function(n,t){return n.index-t.index}),Fn("value")))})}function Mn(n,t,e,r){var u=d(t)?In:_n;u(n,t,a(e),r||m)}function Un(n,t){function e(n){return n?r(n):void u(e)}var r=U(t||m),u=a(Tn(n));e()}function zn(n,t,e,r){r=g(r||m);var u={},i=a(e);P(n,t,function(n,t,e){i(n,t,function(n,r){return n?e(n):(u[t]=r,void e())})},function(n){r(n,u)})}function Pn(n,t){return t in n}function Vn(n,e){var r=Object.create(null),u=Object.create(null);e=e||gn;var i=a(n),o=ct(function(n,o){var c=e.apply(null,n);Pn(r,c)?lt(function(){o.apply(null,r[c])}):Pn(u,c)?u[c].push(o):(u[c]=[o],i.apply(null,n.concat(function(){var n=t(arguments);r[c]=n;var e=u[c];delete u[c];for(var i=0,o=e.length;i<o;i++)e[i].apply(null,n)})))});return o.memo=r,o.unmemoized=n,o}function qn(n,e,r){r=r||m;var u=d(e)?[]:{};n(e,function(n,e,r){a(n)(function(n,i){arguments.length>2&&(i=t(arguments,1)),u[e]=i,r(n)})},function(n){r(n,u)})}function Dn(n,t){qn(Ie,n,t)}function Rn(n,t,e){qn(z(t),n,e)}function Cn(n,t){if(t=g(t||m),!Vt(n))return t(new TypeError("First argument to race must be an array of functions"));if(!n.length)return t();for(var e=0,r=n.length;e<r;e++)a(n[e])(t)}function $n(n,e,r,u){var i=t(n).reverse();dn(i,e,r,u)}function Wn(n){var e=a(n);return ct(function(n,r){return n.push(function(n,e){if(n)r(null,{error:n});else{var u;u=arguments.length<=2?e:t(arguments,1),r(null,{value:u})}}),e.apply(this,n)})}function Nn(n){var t;return Vt(n)?t=K(n,Wn):(t={},N(n,function(n,e){t[e]=Wn.call(this,n)})),t}function Qn(n,t,e,r){Mn(n,t,function(n,t){e(n,function(n,e){t(n,!e)})},r)}function Gn(n){return function(){return n}}function Hn(n,t,e){function r(n,t){if("object"==typeof t)n.times=+t.times||i,n.intervalFunc="function"==typeof t.interval?t.interval:Gn(+t.interval||o),n.errorFilter=t.errorFilter;else{if("number"!=typeof t&&"string"!=typeof t)throw new Error("Invalid arguments for async.retry");n.times=+t||i}}function u(){f(function(n){n&&l++<c.times&&("function"!=typeof c.errorFilter||c.errorFilter(n))?setTimeout(u,c.intervalFunc(l)):e.apply(null,arguments)})}var i=5,o=0,c={times:i,intervalFunc:Gn(o)};if(arguments.length<3&&"function"==typeof n?(e=t||m,t=n):(r(c,n),e=e||m),"function"!=typeof t)throw new Error("Invalid arguments for async.retry");var f=a(t),l=1;u()}function Jn(n,t){qn(Or,n,t)}function Kn(n,t,e){function r(n,t){var e=n.criteria,r=t.criteria;return e<r?-1:e>r?1:0}var u=a(t);_e(n,function(n,t){u(n,function(e,r){return e?t(e):void t(null,{value:n,criteria:r})})},function(n,t){return n?e(n):void e(null,K(t.sort(r),Fn("value")))})}function Xn(n,t,e){var r=a(n);return ct(function(u,i){function o(){var t=n.name||"anonymous",r=new Error('Callback function "'+t+'" timed out.');r.code="ETIMEDOUT",e&&(r.info=e),f=!0,i(r)}var c,f=!1;u.push(function(){f||(i.apply(null,arguments),clearTimeout(c))}),c=setTimeout(o,t),r.apply(null,u)})}function Yn(n,t,e,r){for(var u=-1,i=iu(uu((t-n)/(e||1)),0),o=Array(i);i--;)o[r?i:++u]=n,n+=e;return o}function Zn(n,t,e,r){var u=a(e);Ue(Yn(0,n,1),t,u,r)}function nt(n,t,e,r){arguments.length<=3&&(r=e,e=t,t=Vt(n)?[]:{}),r=g(r||m);var u=a(e);Ie(n,function(n,e,r){u(t,n,e,r)},function(n){r(n,t)})}function tt(n,e){var r,u=null;e=e||m,Ur(n,function(n,e){a(n)(function(n,i){r=arguments.length>2?t(arguments,1):i,u=n,e(!n)})},function(){e(u,r)})}function et(n){return function(){return(n.unmemoized||n).apply(null,arguments)}}function rt(n,e,r){r=U(r||m);var u=a(e);if(!n())return r(null);var i=function(e){if(e)return r(e);if(n())return u(i);var o=t(arguments,1);r.apply(null,[null].concat(o))};u(i)}function ut(n,t,e){rt(function(){return!n.apply(this,arguments)},t,e)}var it,ot=function(n){var e=t(arguments,1);return function(){var r=t(arguments);return n.apply(null,e.concat(r))}},ct=function(n){return function(){var e=t(arguments),r=e.pop();n.call(this,e,r)}},ft="function"==typeof setImmediate&&setImmediate,at="object"==typeof process&&"function"==typeof process.nextTick;it=ft?setImmediate:at?process.nextTick:r;var lt=u(it),st="function"==typeof Symbol,pt="object"==typeof global&&global&&global.Object===Object&&global,ht="object"==typeof self&&self&&self.Object===Object&&self,yt=pt||ht||Function("return this")(),vt=yt.Symbol,dt=Object.prototype,mt=dt.hasOwnProperty,gt=dt.toString,bt=vt?vt.toStringTag:void 0,jt=Object.prototype,St=jt.toString,kt="[object Null]",Lt="[object Undefined]",Ot=vt?vt.toStringTag:void 0,wt="[object AsyncFunction]",xt="[object Function]",Et="[object GeneratorFunction]",At="[object Proxy]",Tt=9007199254740991,Bt={},Ft="function"==typeof Symbol&&Symbol.iterator,It=function(n){return Ft&&n[Ft]&&n[Ft]()},_t="[object Arguments]",Mt=Object.prototype,Ut=Mt.hasOwnProperty,zt=Mt.propertyIsEnumerable,Pt=S(function(){return arguments}())?S:function(n){return j(n)&&Ut.call(n,"callee")&&!zt.call(n,"callee")},Vt=Array.isArray,qt="object"==typeof n&&n&&!n.nodeType&&n,Dt=qt&&"object"==typeof module&&module&&!module.nodeType&&module,Rt=Dt&&Dt.exports===qt,Ct=Rt?yt.Buffer:void 0,$t=Ct?Ct.isBuffer:void 0,Wt=$t||k,Nt=9007199254740991,Qt=/^(?:0|[1-9]\d*)$/,Gt="[object Arguments]",Ht="[object Array]",Jt="[object Boolean]",Kt="[object Date]",Xt="[object Error]",Yt="[object Function]",Zt="[object Map]",ne="[object Number]",te="[object Object]",ee="[object RegExp]",re="[object Set]",ue="[object String]",ie="[object WeakMap]",oe="[object ArrayBuffer]",ce="[object DataView]",fe="[object Float32Array]",ae="[object Float64Array]",le="[object Int8Array]",se="[object Int16Array]",pe="[object Int32Array]",he="[object Uint8Array]",ye="[object Uint8ClampedArray]",ve="[object Uint16Array]",de="[object Uint32Array]",me={};me[fe]=me[ae]=me[le]=me[se]=me[pe]=me[he]=me[ye]=me[ve]=me[de]=!0,me[Gt]=me[Ht]=me[oe]=me[Jt]=me[ce]=me[Kt]=me[Xt]=me[Yt]=me[Zt]=me[ne]=me[te]=me[ee]=me[re]=me[ue]=me[ie]=!1;var ge="object"==typeof n&&n&&!n.nodeType&&n,be=ge&&"object"==typeof module&&module&&!module.nodeType&&module,je=be&&be.exports===ge,Se=je&&pt.process,ke=function(){try{return Se&&Se.binding&&Se.binding("util")}catch(n){}}(),Le=ke&&ke.isTypedArray,Oe=Le?w(Le):O,we=Object.prototype,xe=we.hasOwnProperty,Ee=Object.prototype,Ae=A(Object.keys,Object),Te=Object.prototype,Be=Te.hasOwnProperty,Fe=V(P,1/0),Ie=function(n,t,e){var r=d(n)?q:Fe;r(n,a(t),e)},_e=D(R),Me=l(_e),Ue=C(R),ze=V(Ue,1),Pe=l(ze),Ve=W(),qe=function(n,e,r){function u(n,t){j.push(function(){f(n,t)})}function i(){if(0===j.length&&0===v)return r(null,y);for(;j.length&&v<e;){var n=j.shift();n()}}function o(n,t){var e=b[n];e||(e=b[n]=[]),e.push(t)}function c(n){var t=b[n]||[];$(t,function(n){n()}),i()}function f(n,e){if(!d){var u=U(function(e,u){if(v--,arguments.length>2&&(u=t(arguments,1)),e){var i={};N(y,function(n,t){i[t]=n}),i[n]=u,d=!0,b=Object.create(null),r(e,i)}else y[n]=u,c(n)});v++;var i=a(e[e.length-1]);e.length>1?i(y,u):i(u)}}function l(){for(var n,t=0;S.length;)n=S.pop(),t++,$(s(n),function(n){0===--k[n]&&S.push(n)});if(t!==h)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function s(t){var e=[];return N(n,function(n,r){Vt(n)&&J(n,t,0)>=0&&e.push(r)}),e}"function"==typeof e&&(r=e,e=null),r=g(r||m);var p=B(n),h=p.length;if(!h)return r(null);e||(e=h);var y={},v=0,d=!1,b=Object.create(null),j=[],S=[],k={};N(n,function(t,e){if(!Vt(t))return u(e,[t]),void S.push(e);var r=t.slice(0,t.length-1),i=r.length;return 0===i?(u(e,t),void S.push(e)):(k[e]=i,void $(r,function(c){if(!n[c])throw new Error("async.auto task `"+e+"` has a non-existent dependency `"+c+"` in "+r.join(", "));o(c,function(){i--,0===i&&u(e,t)})}))}),l(),i()},De="[object Symbol]",Re=1/0,Ce=vt?vt.prototype:void 0,$e=Ce?Ce.toString:void 0,We="\\ud800-\\udfff",Ne="\\u0300-\\u036f",Qe="\\ufe20-\\ufe2f",Ge="\\u20d0-\\u20ff",He=Ne+Qe+Ge,Je="\\ufe0e\\ufe0f",Ke="\\u200d",Xe=RegExp("["+Ke+We+He+Je+"]"),Ye="\\ud800-\\udfff",Ze="\\u0300-\\u036f",nr="\\ufe20-\\ufe2f",tr="\\u20d0-\\u20ff",er=Ze+nr+tr,rr="\\ufe0e\\ufe0f",ur="["+Ye+"]",ir="["+er+"]",or="\\ud83c[\\udffb-\\udfff]",cr="(?:"+ir+"|"+or+")",fr="[^"+Ye+"]",ar="(?:\\ud83c[\\udde6-\\uddff]){2}",lr="[\\ud800-\\udbff][\\udc00-\\udfff]",sr="\\u200d",pr=cr+"?",hr="["+rr+"]?",yr="(?:"+sr+"(?:"+[fr,ar,lr].join("|")+")"+hr+pr+")*",vr=hr+pr+yr,dr="(?:"+[fr+ir+"?",ir,ar,lr,ur].join("|")+")",mr=RegExp(or+"(?="+or+")|"+dr+vr,"g"),gr=/^\s+|\s+$/g,br=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,jr=/,/,Sr=/(=.+)?(\s*)$/,kr=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm;pn.prototype.removeLink=function(n){return n.prev?n.prev.next=n.next:this.head=n.next,n.next?n.next.prev=n.prev:this.tail=n.prev,n.prev=n.next=null,this.length-=1,n},pn.prototype.empty=function(){for(;this.head;)this.shift();return this},pn.prototype.insertAfter=function(n,t){t.prev=n,t.next=n.next,n.next?n.next.prev=t:this.tail=t,n.next=t,this.length+=1},pn.prototype.insertBefore=function(n,t){t.prev=n.prev,t.next=n,n.prev?n.prev.next=t:this.head=t,n.prev=t,this.length+=1},pn.prototype.unshift=function(n){this.head?this.insertBefore(this.head,n):hn(this,n)},pn.prototype.push=function(n){this.tail?this.insertAfter(this.tail,n):hn(this,n)},pn.prototype.shift=function(){return this.head&&this.removeLink(this.head)},pn.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},pn.prototype.toArray=function(){for(var n=Array(this.length),t=this.head,e=0;e<this.length;e++)n[e]=t.data,t=t.next;return n},pn.prototype.remove=function(n){for(var t=this.head;t;){var e=t.next;n(t)&&this.removeLink(t),t=e}return this};var Lr,Or=V(P,1),wr=function(){return mn.apply(null,t(arguments).reverse())},xr=Array.prototype.concat,Er=function(n,e,r,u){u=u||m;var i=a(r);Ue(n,e,function(n,e){i(n,function(n){return n?e(n):e(null,t(arguments,1))})},function(n,t){for(var e=[],r=0;r<t.length;r++)t[r]&&(e=xr.apply(e,t[r]));return u(n,e)})},Ar=V(Er,1/0),Tr=V(Er,1),Br=function(){var n=t(arguments),e=[null].concat(n);return function(){var n=arguments[arguments.length-1];return n.apply(this,e)}},Fr=D(bn(gn,jn)),Ir=C(bn(gn,jn)),_r=V(Ir,1),Mr=Sn("dir"),Ur=V(An,1),zr=D(bn(Bn,Bn)),Pr=C(bn(Bn,Bn)),Vr=V(Pr,1),qr=D(Mn),Dr=C(Mn),Rr=V(Dr,1),Cr=function(n,t,e,r){r=r||m;var u=a(e);Ue(n,t,function(n,t){u(n,function(e,r){return e?t(e):t(null,{key:r,val:n})})},function(n,t){for(var e={},u=Object.prototype.hasOwnProperty,i=0;i<t.length;i++)if(t[i]){var o=t[i].key,c=t[i].val;u.call(e,o)?e[o].push(c):e[o]=[c]}return r(n,e)})},$r=V(Cr,1/0),Wr=V(Cr,1),Nr=Sn("log"),Qr=V(zn,1/0),Gr=V(zn,1);Lr=at?process.nextTick:ft?setImmediate:r;var Hr=u(Lr),Jr=function(n,t){var e=a(n);return yn(function(n,t){e(n[0],t)},t,1)},Kr=function(n,t){var e=Jr(n,t);return e.push=function(n,t,r){if(null==r&&(r=m),"function"!=typeof r)throw new Error("task callback must be a function");if(e.started=!0,Vt(n)||(n=[n]),0===n.length)return lt(function(){e.drain()});t=t||0;for(var u=e._tasks.head;u&&t>=u.priority;)u=u.next;for(var i=0,o=n.length;i<o;i++){var c={data:n[i],priority:t,callback:r};u?e._tasks.insertBefore(u,c):e._tasks.push(c)}lt(e.process)},delete e.unshift,e},Xr=D(Qn),Yr=C(Qn),Zr=V(Yr,1),nu=function(n,t){t||(t=n,n=null);var e=a(t);return ct(function(t,r){function u(n){e.apply(null,t.concat(n))}n?Hn(n,u,r):Hn(u,r)})},tu=D(bn(Boolean,gn)),eu=C(bn(Boolean,gn)),ru=V(eu,1),uu=Math.ceil,iu=Math.max,ou=V(Zn,1/0),cu=V(Zn,1),fu=function(n,e){function r(t){var e=a(n[i++]);t.push(U(u)),e.apply(null,t)}function u(u){return u||i===n.length?e.apply(null,arguments):void r(t(arguments,1))}if(e=g(e||m),!Vt(n))return e(new Error("First argument to waterfall must be an array of functions"));if(!n.length)return e();var i=0;r([])},au={apply:ot,applyEach:Me,applyEachSeries:Pe,asyncify:i,auto:qe,autoInject:sn,cargo:vn,compose:wr,concat:Ar,concatLimit:Er,concatSeries:Tr,constant:Br,detect:Fr,detectLimit:Ir,detectSeries:_r,dir:Mr,doDuring:kn,doUntil:On,doWhilst:Ln,during:wn,each:En,eachLimit:An,eachOf:Ie,eachOfLimit:P,eachOfSeries:Or,eachSeries:Ur,ensureAsync:Tn,every:zr,everyLimit:Pr,everySeries:Vr,filter:qr,filterLimit:Dr,filterSeries:Rr,forever:Un,groupBy:$r,groupByLimit:Cr,groupBySeries:Wr,log:Nr,map:_e,mapLimit:Ue,mapSeries:ze,mapValues:Qr,mapValuesLimit:zn,mapValuesSeries:Gr,memoize:Vn,nextTick:Hr,parallel:Dn,parallelLimit:Rn,priorityQueue:Kr,queue:Jr,race:Cn,reduce:dn,reduceRight:$n,reflect:Wn,reflectAll:Nn,reject:Xr,rejectLimit:Yr,rejectSeries:Zr,retry:Hn,retryable:nu,seq:mn,series:Jn,setImmediate:lt,some:tu,someLimit:eu,someSeries:ru,sortBy:Kn,timeout:Xn,times:ou,timesLimit:Zn,timesSeries:cu,transform:nt,tryEach:tt,unmemoize:et,until:ut,waterfall:fu,whilst:rt,all:zr,allLimit:Pr,allSeries:Vr,any:tu,anyLimit:eu,anySeries:ru,find:Fr,findLimit:Ir,findSeries:_r,forEach:En,forEachSeries:Ur,forEachLimit:An,forEachOf:Ie,forEachOfSeries:Or,forEachOfLimit:P,inject:dn,foldl:dn,foldr:$n,select:qr,selectLimit:Dr,selectSeries:Rr,wrapSync:i};n.default=au,n.apply=ot,n.applyEach=Me,n.applyEachSeries=Pe,n.asyncify=i,n.auto=qe,n.autoInject=sn,n.cargo=vn,n.compose=wr,n.concat=Ar,n.concatLimit=Er,n.concatSeries=Tr,n.constant=Br,n.detect=Fr,n.detectLimit=Ir,n.detectSeries=_r,n.dir=Mr,n.doDuring=kn,n.doUntil=On,n.doWhilst=Ln,n.during=wn,n.each=En,n.eachLimit=An,n.eachOf=Ie,n.eachOfLimit=P,n.eachOfSeries=Or,n.eachSeries=Ur,n.ensureAsync=Tn,n.every=zr,n.everyLimit=Pr,n.everySeries=Vr,n.filter=qr,n.filterLimit=Dr,n.filterSeries=Rr,n.forever=Un,n.groupBy=$r,n.groupByLimit=Cr,n.groupBySeries=Wr,n.log=Nr,n.map=_e,n.mapLimit=Ue,n.mapSeries=ze,n.mapValues=Qr,n.mapValuesLimit=zn,n.mapValuesSeries=Gr,n.memoize=Vn,n.nextTick=Hr,n.parallel=Dn,n.parallelLimit=Rn,n.priorityQueue=Kr,n.queue=Jr,n.race=Cn,n.reduce=dn,n.reduceRight=$n,n.reflect=Wn,n.reflectAll=Nn,n.reject=Xr,n.rejectLimit=Yr,n.rejectSeries=Zr,n.retry=Hn,n.retryable=nu,n.seq=mn,n.series=Jn,n.setImmediate=lt,n.some=tu,n.someLimit=eu,n.someSeries=ru,n.sortBy=Kn,n.timeout=Xn,n.times=ou,n.timesLimit=Zn,n.timesSeries=cu,n.transform=nt,n.tryEach=tt,n.unmemoize=et,n.until=ut,n.waterfall=fu,n.whilst=rt,n.all=zr,n.allLimit=Pr,n.allSeries=Vr,n.any=tu,n.anyLimit=eu,n.anySeries=ru,n.find=Fr,n.findLimit=Ir,n.findSeries=_r,n.forEach=En,n.forEachSeries=Ur,n.forEachLimit=An,n.forEachOf=Ie,n.forEachOfSeries=Or,n.forEachOfLimit=P,n.inject=dn,n.foldl=dn,n.foldr=$n,n.select=qr,n.selectLimit=Dr,n.selectSeries=Rr,n.wrapSync=i,Object.defineProperty(n,"__esModule",{value:!0})}); -//# sourceMappingURL=async.min.map
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/dist/async.min.map b/node_modules/webpack/node_modules/async/dist/async.min.map deleted file mode 100644 index 6cd63ab34..000000000 --- a/node_modules/webpack/node_modules/async/dist/async.min.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["build/dist/async.js"],"names":["global","factory","exports","module","define","amd","async","this","slice","arrayLike","start","newLen","Math","max","length","newArr","Array","idx","isObject","value","type","fallback","fn","setTimeout","wrap","defer","args","arguments","apply","asyncify","func","initialParams","callback","result","e","then","invokeCallback","err","message","Error","error","setImmediate$1","rethrow","isAsync","supportsSymbol","Symbol","toStringTag","wrapAsync","asyncFn","applyEach$1","eachfn","fns","go","that","cb","concat","getRawTag","isOwn","hasOwnProperty","call","symToStringTag$1","tag","undefined","unmasked","nativeObjectToString","objectToString","nativeObjectToString$1","baseGetTag","undefinedTag","nullTag","symToStringTag","Object","isFunction","funcTag","genTag","asyncTag","proxyTag","isLength","MAX_SAFE_INTEGER","isArrayLike","noop","once","callFn","baseTimes","n","iteratee","index","isObjectLike","baseIsArguments","argsTag","stubFalse","isIndex","MAX_SAFE_INTEGER$1","reIsUint","test","baseIsTypedArray","typedArrayTags","baseUnary","arrayLikeKeys","inherited","isArr","isArray","isArg","isArguments","isBuff","isBuffer","isType","isTypedArray","skipIndexes","String","key","hasOwnProperty$1","push","isPrototype","Ctor","constructor","proto","prototype","objectProto$5","overArg","transform","arg","baseKeys","object","nativeKeys","hasOwnProperty$3","keys","createArrayIterator","coll","i","len","createES2015Iterator","iterator","item","next","done","createObjectIterator","obj","okeys","getIterator","onlyOnce","_eachOfLimit","limit","iterateeCallback","running","breakLoop","replenish","elem","nextElem","eachOfLimit","doLimit","iterable","eachOfArrayLike","iteratorCallback","completed","doParallel","eachOf","_asyncMap","arr","results","counter","_iteratee","_","v","doParallelLimit","arrayEach","array","createBaseFor","fromRight","keysFunc","props","baseForOwn","baseFor","baseFindIndex","predicate","fromIndex","baseIsNaN","strictIndexOf","baseIndexOf","arrayMap","isSymbol","symbolTag","baseToString","symbolToString","INFINITY","baseSlice","end","castSlice","charsEndIndex","strSymbols","chrSymbols","charsStartIndex","asciiToArray","string","split","hasUnicode","reHasUnicode","unicodeToArray","match","reUnicode","stringToArray","toString","trim","chars","guard","replace","reTrim","join","parseParams","STRIP_COMMENTS","FN_ARGS","FN_ARG_SPLIT","map","FN_ARG","autoInject","tasks","newTasks","taskFn","newTask","taskCb","newArgs","params","name","fnIsAsync","hasNoDeps","pop","auto","DLL","head","tail","setInitial","dll","node","queue","worker","concurrency","payload","_insert","data","insertAtFront","q","started","idle","drain","l","_tasks","unshift","processingScheduled","process","_next","numRunning","task","workersList","shift","splice","buffer","unsaturated","_worker","isProcessing","saturated","empty","paused","kill","remove","testFn","min","pause","resume","cargo","reduce","memo","eachOfSeries","x","seq","_functions","newargs","nextargs","identity","_createTester","check","getResult","testResult","testPassed","_findGetResult","consoleFunc","console","doDuring","_test","truth","_fn","doWhilst","doUntil","during","_withoutIndex","eachLimit","eachLimit$1","ensureAsync","sync","innerArgs","notId","baseProperty","filterArray","truthValues","filterGeneric","sort","a","b","_filter","filter","forever","errback","mapValuesLimit","newObj","val","has","memoize","hasher","create","queues","memoized","unmemoized","_parallel","parallelLimit","parallelLimit$1","race","TypeError","reduceRight","reversed","reverse","reflect","reflectCallback","cbArg","reflectAll","reject$1","constant$1","retry","opts","parseTimes","acc","t","times","DEFAULT_TIMES","intervalFunc","interval","DEFAULT_INTERVAL","errorFilter","retryAttempt","_task","attempt","options","series","sortBy","comparator","left","right","criteria","timeout","milliseconds","info","timeoutCallback","code","timedOut","timer","clearTimeout","baseRange","step","nativeMax","nativeCeil","timeLimit","count","mapLimit","accumulator","k","tryEach","eachSeries","res","unmemoize","whilst","until","_defer","callArgs","hasSetImmediate","setImmediate","hasNextTick","nextTick","freeGlobal","freeSelf","self","root","Function","Symbol$1","objectProto","objectProto$1","iteratorSymbol","objectProto$3","hasOwnProperty$2","propertyIsEnumerable","freeExports","nodeType","freeModule","moduleExports","Buffer","nativeIsBuffer","argsTag$1","arrayTag","boolTag","dateTag","errorTag","funcTag$1","mapTag","numberTag","objectTag","regexpTag","setTag","stringTag","weakMapTag","arrayBufferTag","dataViewTag","float32Tag","float64Tag","int8Tag","int16Tag","int32Tag","uint8Tag","uint8ClampedTag","uint16Tag","uint32Tag","freeExports$1","freeModule$1","moduleExports$1","freeProcess","nodeUtil","binding","nodeIsTypedArray","objectProto$2","objectProto$4","eachOfGeneric","Infinity","eachOfImplementation","applyEach","mapSeries","applyEachSeries","enqueueTask","readyTasks","runTask","processQueue","runningTasks","run","addListener","taskName","taskListeners","listeners","taskComplete","hasError","taskCallback","safeResults","rkey","checkForDeadlocks","currentTask","readyToCheck","getDependents","dependent","uncheckedDependencies","numTasks","keys$$1","dependencies","remainingDependencies","dependencyName","symbolProto","rsAstralRange","rsComboMarksRange","reComboHalfMarksRange","rsComboSymbolsRange","rsComboRange","rsVarRange","rsZWJ","RegExp","rsAstralRange$1","rsComboMarksRange$1","reComboHalfMarksRange$1","rsComboSymbolsRange$1","rsComboRange$1","rsVarRange$1","rsAstral","rsCombo","rsFitz","rsModifier","rsNonAstral","rsRegional","rsSurrPair","rsZWJ$1","reOptMod","rsOptVar","rsOptJoin","rsSeq","rsSymbol","removeLink","prev","insertAfter","newNode","insertBefore","toArray","curr","_defer$1","compose","_concat","concatLimit","mapResults","concatSeries","constant","values","detect","detectLimit","detectSeries","dir","every","everyLimit","everySeries","filterLimit","filterSeries","groupByLimit","groupBy","groupBySeries","log","mapValues","mapValuesSeries","queue$1","items","priorityQueue","priority","nextNode","reject","rejectLimit","rejectSeries","retryable","some","Boolean","someLimit","someSeries","ceil","timesSeries","waterfall","nextTask","taskIndex","each","parallel","timesLimit","all","allLimit","allSeries","any","anyLimit","anySeries","find","findLimit","findSeries","forEach","forEachSeries","forEachLimit","forEachOf","forEachOfSeries","forEachOfLimit","inject","foldl","foldr","select","selectLimit","selectSeries","wrapSync","defineProperty"],"mappings":"CAAC,SAAUA,EAAQC,GACE,gBAAZC,UAA0C,mBAAXC,QAAyBF,EAAQC,SACrD,kBAAXE,SAAyBA,OAAOC,IAAMD,QAAQ,WAAYH,GAChEA,EAASD,EAAOM,MAAQN,EAAOM,YAChCC,KAAM,SAAWL,GAAW,YAE9B,SAASM,GAAMC,EAAWC,GACtBA,GAAc,CAGd,KAAI,GAFAC,GAASC,KAAKC,IAAIJ,EAAUK,OAASJ,EAAO,GAC5CK,EAASC,MAAML,GACXM,EAAM,EAAGA,EAAMN,EAAQM,IAC3BF,EAAOE,GAAOR,EAAUC,EAAQO,EAEpC,OAAOF,GAyFX,QAASG,GAASC,GAChB,GAAIC,SAAcD,EAClB,OAAgB,OAATA,IAA0B,UAARC,GAA4B,YAARA,GAM/C,QAASC,GAASC,GACdC,WAAWD,EAAI,GAGnB,QAASE,GAAKC,GACV,MAAO,UAAUH,GACb,GAAII,GAAOlB,EAAMmB,UAAW,EAC5BF,GAAM,WACFH,EAAGM,MAAM,KAAMF,MAyE3B,QAASG,GAASC,GACd,MAAOC,IAAc,SAAUL,EAAMM,GACjC,GAAIC,EACJ,KACIA,EAASH,EAAKF,MAAMrB,KAAMmB,GAC5B,MAAOQ,GACL,MAAOF,GAASE,GAGhBhB,EAASe,IAAkC,kBAAhBA,GAAOE,KAClCF,EAAOE,KAAK,SAAShB,GACjBiB,EAAeJ,EAAU,KAAMb,IAChC,SAASkB,GACRD,EAAeJ,EAAUK,EAAIC,QAAUD,EAAM,GAAIE,OAAMF,MAG3DL,EAAS,KAAMC,KAK3B,QAASG,GAAeJ,EAAUQ,EAAOrB,GACrC,IACIa,EAASQ,EAAOrB,GAClB,MAAOe,GACLO,GAAeC,EAASR,IAIhC,QAASQ,GAAQF,GACb,KAAMA,GAKV,QAASG,GAAQrB,GACb,MAAOsB,KAA6C,kBAA3BtB,EAAGuB,OAAOC,aAGvC,QAASC,GAAUC,GACf,MAAOL,GAAQK,GAAWnB,EAASmB,GAAWA,EAGlD,QAASC,GAAYC,GACjB,MAAO,UAASC,GACZ,GAAIzB,GAAOlB,EAAMmB,UAAW,GACxByB,EAAKrB,GAAc,SAASL,EAAMM,GAClC,GAAIqB,GAAO9C,IACX,OAAO2C,GAAOC,EAAK,SAAU7B,EAAIgC,GAC7BP,EAAUzB,GAAIM,MAAMyB,EAAM3B,EAAK6B,OAAOD,KACvCtB,IAEP,OAAIN,GAAKZ,OACEsC,EAAGxB,MAAMrB,KAAMmB,GAGf0B,GAwCnB,QAASI,GAAUrC,GACjB,GAAIsC,GAAQC,GAAeC,KAAKxC,EAAOyC,IACnCC,EAAM1C,EAAMyC,GAEhB,KACEzC,EAAMyC,IAAoBE,MAC1B,IAAIC,IAAW,EACf,MAAO7B,IAET,GAAID,GAAS+B,GAAqBL,KAAKxC,EAQvC,OAPI4C,KACEN,EACFtC,EAAMyC,IAAoBC,QAEnB1C,GAAMyC,KAGV3B,EAoBT,QAASgC,GAAe9C,GACtB,MAAO+C,IAAuBP,KAAKxC,GAiBrC,QAASgD,GAAWhD,GAClB,MAAa,OAATA,EACe2C,SAAV3C,EAAsBiD,GAAeC,GAEtCC,IAAkBA,KAAkBC,QAAOpD,GAC/CqC,EAAUrC,GACV8C,EAAe9C,GA0BrB,QAASqD,GAAWrD,GAClB,IAAKD,EAASC,GACZ,OAAO,CAIT,IAAI0C,GAAMM,EAAWhD,EACrB,OAAO0C,IAAOY,IAAWZ,GAAOa,IAAUb,GAAOc,IAAYd,GAAOe,GAgCtE,QAASC,GAAS1D,GAChB,MAAuB,gBAATA,IACZA,GAAQ,GAAMA,EAAQ,GAAK,GAAKA,GAAS2D,GA4B7C,QAASC,GAAY5D,GACnB,MAAgB,OAATA,GAAiB0D,EAAS1D,EAAML,UAAY0D,EAAWrD,GAmBhE,QAAS6D,MAIT,QAASC,GAAK3D,GACV,MAAO,YACH,GAAW,OAAPA,EAAJ,CACA,GAAI4D,GAAS5D,CACbA,GAAK,KACL4D,EAAOtD,MAAMrB,KAAMoB,aAmB3B,QAASwD,GAAUC,EAAGC,GAIpB,IAHA,GAAIC,IAAQ,EACRrD,EAASjB,MAAMoE,KAEVE,EAAQF,GACfnD,EAAOqD,GAASD,EAASC,EAE3B,OAAOrD,GA2BT,QAASsD,GAAapE,GACpB,MAAgB,OAATA,GAAiC,gBAATA,GAajC,QAASqE,GAAgBrE,GACvB,MAAOoE,GAAapE,IAAUgD,EAAWhD,IAAUsE,GAyErD,QAASC,KACP,OAAO,EAmDT,QAASC,GAAQxE,EAAOL,GAEtB,MADAA,GAAmB,MAAVA,EAAiB8E,GAAqB9E,IACtCA,IACU,gBAATK,IAAqB0E,GAASC,KAAK3E,KAC1CA,GAAQ,GAAMA,EAAQ,GAAK,GAAKA,EAAQL,EAqD7C,QAASiF,GAAiB5E,GACxB,MAAOoE,GAAapE,IAClB0D,EAAS1D,EAAML,WAAakF,GAAe7B,EAAWhD,IAU1D,QAAS8E,GAAUnE,GACjB,MAAO,UAASX,GACd,MAAOW,GAAKX,IA2DhB,QAAS+E,GAAc/E,EAAOgF,GAC5B,GAAIC,GAAQC,GAAQlF,GAChBmF,GAASF,GAASG,GAAYpF,GAC9BqF,GAAUJ,IAAUE,GAASG,GAAStF,GACtCuF,GAAUN,IAAUE,IAAUE,GAAUG,GAAaxF,GACrDyF,EAAcR,GAASE,GAASE,GAAUE,EAC1CzE,EAAS2E,EAAczB,EAAUhE,EAAML,OAAQ+F,WAC/C/F,EAASmB,EAAOnB,MAEpB,KAAK,GAAIgG,KAAO3F,IACTgF,IAAaY,GAAiBpD,KAAKxC,EAAO2F,IACzCF,IAEQ,UAAPE,GAECN,IAAkB,UAAPM,GAA0B,UAAPA,IAE9BJ,IAAkB,UAAPI,GAA0B,cAAPA,GAA8B,cAAPA,IAEtDnB,EAAQmB,EAAKhG,KAElBmB,EAAO+E,KAAKF,EAGhB,OAAO7E,GAaT,QAASgF,GAAY9F,GACnB,GAAI+F,GAAO/F,GAASA,EAAMgG,YACtBC,EAAwB,kBAARF,IAAsBA,EAAKG,WAAcC,EAE7D,OAAOnG,KAAUiG,EAWnB,QAASG,GAAQzF,EAAM0F,GACrB,MAAO,UAASC,GACd,MAAO3F,GAAK0F,EAAUC,KAoB1B,QAASC,GAASC,GAChB,IAAKV,EAAYU,GACf,MAAOC,IAAWD,EAEpB,IAAI1F,KACJ,KAAK,GAAI6E,KAAOvC,QAAOoD,GACjBE,GAAiBlE,KAAKgE,EAAQb,IAAe,eAAPA,GACxC7E,EAAO+E,KAAKF,EAGhB,OAAO7E,GA+BT,QAAS6F,GAAKH,GACZ,MAAO5C,GAAY4C,GAAUzB,EAAcyB,GAAUD,EAASC,GAGhE,QAASI,GAAoBC,GACzB,GAAIC,IAAI,EACJC,EAAMF,EAAKlH,MACf,OAAO,YACH,QAASmH,EAAIC,GAAO/G,MAAO6G,EAAKC,GAAInB,IAAKmB,GAAK,MAItD,QAASE,GAAqBC,GAC1B,GAAIH,IAAI,CACR,OAAO,YACH,GAAII,GAAOD,EAASE,MACpB,OAAID,GAAKE,KACE,MACXN,KACQ9G,MAAOkH,EAAKlH,MAAO2F,IAAKmB,KAIxC,QAASO,GAAqBC,GAC1B,GAAIC,GAAQZ,EAAKW,GACbR,GAAI,EACJC,EAAMQ,EAAM5H,MAChB,OAAO,YACH,GAAIgG,GAAM4B,IAAQT,EAClB,OAAOA,GAAIC,GAAO/G,MAAOsH,EAAI3B,GAAMA,IAAKA,GAAO,MAIvD,QAASsB,GAASJ,GACd,GAAIjD,EAAYiD,GACZ,MAAOD,GAAoBC,EAG/B,IAAII,GAAWO,GAAYX,EAC3B,OAAOI,GAAWD,EAAqBC,GAAYI,EAAqBR,GAG5E,QAASY,GAAStH,GACd,MAAO,YACH,GAAW,OAAPA,EAAa,KAAM,IAAIiB,OAAM,+BACjC,IAAI2C,GAAS5D,CACbA,GAAK,KACL4D,EAAOtD,MAAMrB,KAAMoB,YAI3B,QAASkH,GAAaC,GAClB,MAAO,UAAUL,EAAKpD,EAAUrD,GAS5B,QAAS+G,GAAiB1G,EAAKlB,GAE3B,GADA6H,GAAW,EACP3G,EACAkG,GAAO,EACPvG,EAASK,OAER,CAAA,GAAIlB,IAAU8H,IAAcV,GAAQS,GAAW,EAEhD,MADAT,IAAO,EACAvG,EAAS,KAGhBkH,MAIR,QAASA,KACL,KAAOF,EAAUF,IAAUP,GAAM,CAC7B,GAAIY,GAAOC,GACX,IAAa,OAATD,EAKA,MAJAZ,IAAO,OACHS,GAAW,GACXhH,EAAS,MAIjBgH,IAAW,EACX3D,EAAS8D,EAAKhI,MAAOgI,EAAKrC,IAAK8B,EAASG,KAjChD,GADA/G,EAAWiD,EAAKjD,GAAYgD,GACxB8D,GAAS,IAAML,EACf,MAAOzG,GAAS,KAEpB,IAAIoH,GAAWhB,EAASK,GACpBF,GAAO,EACPS,EAAU,CAgCdE,MAwBR,QAASG,GAAYrB,EAAMc,EAAOzD,EAAUrD,GACxC6G,EAAaC,GAAOd,EAAMjF,EAAUsC,GAAWrD,GAGnD,QAASsH,GAAQhI,EAAIwH,GACjB,MAAO,UAAUS,EAAUlE,EAAUrD,GACjC,MAAOV,GAAGiI,EAAUT,EAAOzD,EAAUrD,IAK7C,QAASwH,GAAgBxB,EAAM3C,EAAUrD,GASrC,QAASyH,GAAiBpH,EAAKlB,GACvBkB,EACAL,EAASK,KACCqH,IAAc5I,GAAWK,IAAU8H,IAC7CjH,EAAS,MAZjBA,EAAWiD,EAAKjD,GAAYgD,EAC5B,IAAIM,GAAQ,EACRoE,EAAY,EACZ5I,EAASkH,EAAKlH,MAalB,KAZe,IAAXA,GACAkB,EAAS,MAWNsD,EAAQxE,EAAQwE,IACnBD,EAAS2C,EAAK1C,GAAQA,EAAOsD,EAASa,IAmD9C,QAASE,GAAWrI,GAChB,MAAO,UAAUmH,EAAKpD,EAAUrD,GAC5B,MAAOV,GAAGsI,GAAQnB,EAAK1F,EAAUsC,GAAWrD,IAIpD,QAAS6H,GAAU3G,EAAQ4G,EAAKzE,EAAUrD,GACtCA,EAAWA,GAAYgD,EACvB8E,EAAMA,KACN,IAAIC,MACAC,EAAU,EACVC,EAAYlH,EAAUsC,EAE1BnC,GAAO4G,EAAK,SAAU3I,EAAO+I,EAAGlI,GAC5B,GAAIsD,GAAQ0E,GACZC,GAAU9I,EAAO,SAAUkB,EAAK8H,GAC5BJ,EAAQzE,GAAS6E,EACjBnI,EAASK,MAEd,SAAUA,GACTL,EAASK,EAAK0H,KA6EtB,QAASK,GAAgB9I,GACrB,MAAO,UAAUmH,EAAKK,EAAOzD,EAAUrD,GACnC,MAAOV,GAAGuH,EAAaC,GAAQL,EAAK1F,EAAUsC,GAAWrD,IA2EjE,QAASqI,GAAUC,EAAOjF,GAIxB,IAHA,GAAIC,IAAQ,EACRxE,EAAkB,MAATwJ,EAAgB,EAAIA,EAAMxJ,SAE9BwE,EAAQxE,GACXuE,EAASiF,EAAMhF,GAAQA,EAAOgF,MAAW,IAI/C,MAAOA,GAUT,QAASC,GAAcC,GACrB,MAAO,UAAS7C,EAAQtC,EAAUoF,GAMhC,IALA,GAAInF,IAAQ,EACRiE,EAAWhF,OAAOoD,GAClB+C,EAAQD,EAAS9C,GACjB7G,EAAS4J,EAAM5J,OAEZA,KAAU,CACf,GAAIgG,GAAM4D,EAAMF,EAAY1J,IAAWwE,EACvC,IAAID,EAASkE,EAASzC,GAAMA,EAAKyC,MAAc,EAC7C,MAGJ,MAAO5B,IAyBX,QAASgD,GAAWhD,EAAQtC,GAC1B,MAAOsC,IAAUiD,GAAQjD,EAAQtC,EAAUyC,GAc7C,QAAS+C,GAAcP,EAAOQ,EAAWC,EAAWP,GAIlD,IAHA,GAAI1J,GAASwJ,EAAMxJ,OACfwE,EAAQyF,GAAaP,EAAY,GAAI,GAEjCA,EAAYlF,MAAYA,EAAQxE,GACtC,GAAIgK,EAAUR,EAAMhF,GAAQA,EAAOgF,GACjC,MAAOhF,EAGX,QAAO,EAUT,QAAS0F,GAAU7J,GACjB,MAAOA,KAAUA,EAanB,QAAS8J,GAAcX,EAAOnJ,EAAO4J,GAInC,IAHA,GAAIzF,GAAQyF,EAAY,EACpBjK,EAASwJ,EAAMxJ,SAEVwE,EAAQxE,GACf,GAAIwJ,EAAMhF,KAAWnE,EACnB,MAAOmE,EAGX,QAAO,EAYT,QAAS4F,GAAYZ,EAAOnJ,EAAO4J,GACjC,MAAO5J,KAAUA,EACb8J,EAAcX,EAAOnJ,EAAO4J,GAC5BF,EAAcP,EAAOU,EAAWD,GAkQtC,QAASI,GAASb,EAAOjF,GAKvB,IAJA,GAAIC,IAAQ,EACRxE,EAAkB,MAATwJ,EAAgB,EAAIA,EAAMxJ,OACnCmB,EAASjB,MAAMF,KAEVwE,EAAQxE,GACfmB,EAAOqD,GAASD,EAASiF,EAAMhF,GAAQA,EAAOgF,EAEhD,OAAOrI,GAuBT,QAASmJ,GAASjK,GAChB,MAAuB,gBAATA,IACXoE,EAAapE,IAAUgD,EAAWhD,IAAUkK,GAkBjD,QAASC,GAAanK,GAEpB,GAAoB,gBAATA,GACT,MAAOA,EAET,IAAIkF,GAAQlF,GAEV,MAAOgK,GAAShK,EAAOmK,GAAgB,EAEzC,IAAIF,EAASjK,GACX,MAAOoK,IAAiBA,GAAe5H,KAAKxC,GAAS,EAEvD,IAAIc,GAAUd,EAAQ,EACtB,OAAkB,KAAVc,GAAkB,EAAId,IAAWqK,GAAY,KAAOvJ,EAY9D,QAASwJ,GAAUnB,EAAO5J,EAAOgL,GAC/B,GAAIpG,IAAQ,EACRxE,EAASwJ,EAAMxJ,MAEfJ,GAAQ,IACVA,GAASA,EAAQI,EAAS,EAAKA,EAASJ,GAE1CgL,EAAMA,EAAM5K,EAASA,EAAS4K,EAC1BA,EAAM,IACRA,GAAO5K,GAETA,EAASJ,EAAQgL,EAAM,EAAMA,EAAMhL,IAAW,EAC9CA,KAAW,CAGX,KADA,GAAIuB,GAASjB,MAAMF,KACVwE,EAAQxE,GACfmB,EAAOqD,GAASgF,EAAMhF,EAAQ5E,EAEhC,OAAOuB,GAYT,QAAS0J,IAAUrB,EAAO5J,EAAOgL,GAC/B,GAAI5K,GAASwJ,EAAMxJ,MAEnB,OADA4K,GAAc5H,SAAR4H,EAAoB5K,EAAS4K,GAC1BhL,GAASgL,GAAO5K,EAAUwJ,EAAQmB,EAAUnB,EAAO5J,EAAOgL,GAYrE,QAASE,IAAcC,EAAYC,GAGjC,IAFA,GAAIxG,GAAQuG,EAAW/K,OAEhBwE,KAAW4F,EAAYY,EAAYD,EAAWvG,GAAQ,IAAK,IAClE,MAAOA,GAYT,QAASyG,IAAgBF,EAAYC,GAInC,IAHA,GAAIxG,IAAQ,EACRxE,EAAS+K,EAAW/K,SAEfwE,EAAQxE,GAAUoK,EAAYY,EAAYD,EAAWvG,GAAQ,IAAK,IAC3E,MAAOA,GAUT,QAAS0G,IAAaC,GACpB,MAAOA,GAAOC,MAAM,IAwBtB,QAASC,IAAWF,GAClB,MAAOG,IAAatG,KAAKmG,GAsC3B,QAASI,IAAeJ,GACtB,MAAOA,GAAOK,MAAMC,QAUtB,QAASC,IAAcP,GACrB,MAAOE,IAAWF,GACdI,GAAeJ,GACfD,GAAaC,GAwBnB,QAASQ,IAAStL,GAChB,MAAgB,OAATA,EAAgB,GAAKmK,EAAanK,GA4B3C,QAASuL,IAAKT,EAAQU,EAAOC,GAE3B,GADAX,EAASQ,GAASR,GACdA,IAAWW,GAAmB9I,SAAV6I,GACtB,MAAOV,GAAOY,QAAQC,GAAQ,GAEhC,KAAKb,KAAYU,EAAQrB,EAAaqB,IACpC,MAAOV,EAET,IAAIJ,GAAaW,GAAcP,GAC3BH,EAAaU,GAAcG,GAC3BjM,EAAQqL,GAAgBF,EAAYC,GACpCJ,EAAME,GAAcC,EAAYC,GAAc,CAElD,OAAOH,IAAUE,EAAYnL,EAAOgL,GAAKqB,KAAK,IAQhD,QAASC,IAAYlL,GAOjB,MANAA,GAAOA,EAAK2K,WAAWI,QAAQI,GAAgB,IAC/CnL,EAAOA,EAAKwK,MAAMY,IAAS,GAAGL,QAAQ,IAAK,IAC3C/K,EAAOA,EAAOA,EAAKoK,MAAMiB,OACzBrL,EAAOA,EAAKsL,IAAI,SAAU3F,GACtB,MAAOiF,IAAKjF,EAAIoF,QAAQQ,GAAQ,OAuFxC,QAASC,IAAWC,EAAOvL,GACvB,GAAIwL,KAEJ7C,GAAW4C,EAAO,SAAUE,EAAQ3G,GA2BhC,QAAS4G,GAAQ3D,EAAS4D,GACtB,GAAIC,GAAUzC,EAAS0C,EAAQ,SAAUC,GACrC,MAAO/D,GAAQ+D,IAEnBF,GAAQ5G,KAAK2G,GACb5K,EAAU0K,GAAQ7L,MAAM,KAAMgM,GA/BlC,GAAIC,GACAE,EAAYpL,EAAQ8K,GACpBO,GACED,GAA+B,IAAlBN,EAAO3M,QACrBiN,GAA+B,IAAlBN,EAAO3M,MAEzB,IAAIuF,GAAQoH,GACRI,EAASJ,EAAOjN,MAAM,GAAG,GACzBiN,EAASA,EAAOA,EAAO3M,OAAS,GAEhC0M,EAAS1G,GAAO+G,EAAOtK,OAAOsK,EAAO/M,OAAS,EAAI4M,EAAUD,OACzD,IAAIO,EAEPR,EAAS1G,GAAO2G,MACb,CAEH,GADAI,EAASb,GAAYS,GACC,IAAlBA,EAAO3M,SAAiBiN,GAA+B,IAAlBF,EAAO/M,OAC5C,KAAM,IAAIyB,OAAM,yDAIfwL,IAAWF,EAAOI,MAEvBT,EAAS1G,GAAO+G,EAAOtK,OAAOmK,MAYtCQ,GAAKV,EAAUxL,GAOnB,QAASmM,MACL5N,KAAK6N,KAAO7N,KAAK8N,KAAO,KACxB9N,KAAKO,OAAS,EAGlB,QAASwN,IAAWC,EAAKC,GACrBD,EAAIzN,OAAS,EACbyN,EAAIH,KAAOG,EAAIF,KAAOG,EA6E1B,QAASC,IAAMC,EAAQC,EAAaC,GAahC,QAASC,GAAQC,EAAMC,EAAe/M,GAClC,GAAgB,MAAZA,GAAwC,kBAAbA,GAC3B,KAAM,IAAIO,OAAM,mCAMpB,IAJAyM,EAAEC,SAAU,EACP5I,GAAQyI,KACTA,GAAQA,IAEQ,IAAhBA,EAAKhO,QAAgBkO,EAAEE,OAEvB,MAAOzM,IAAe,WAClBuM,EAAEG,SAIV,KAAK,GAAIlH,GAAI,EAAGmH,EAAIN,EAAKhO,OAAQmH,EAAImH,EAAGnH,IAAK,CACzC,GAAII,IACAyG,KAAMA,EAAK7G,GACXjG,SAAUA,GAAYgD,EAGtB+J,GACAC,EAAEK,OAAOC,QAAQjH,GAEjB2G,EAAEK,OAAOrI,KAAKqB,GAIjBkH,IACDA,GAAsB,EACtB9M,GAAe,WACX8M,GAAsB,EACtBP,EAAEQ,aAKd,QAASC,GAAMlC,GACX,MAAO,UAASlL,GACZqN,GAAc,CAEd,KAAK,GAAIzH,GAAI,EAAGmH,EAAI7B,EAAMzM,OAAQmH,EAAImH,EAAGnH,IAAK,CAC1C,GAAI0H,GAAOpC,EAAMtF,GAEb3C,EAAQ4F,EAAY0E,EAAaD,EAAM,EAC7B,KAAVrK,EACAsK,EAAYC,QACLvK,EAAQ,GACfsK,EAAYE,OAAOxK,EAAO,GAG9BqK,EAAK3N,SAASJ,MAAM+N,EAAMhO,WAEf,MAAPU,GACA2M,EAAExM,MAAMH,EAAKsN,EAAKb,MAItBY,GAAeV,EAAEL,YAAcK,EAAEe,QACjCf,EAAEgB,cAGFhB,EAAEE,QACFF,EAAEG,QAENH,EAAEQ,WA7EV,GAAmB,MAAfb,EACAA,EAAc,MAEb,IAAmB,IAAhBA,EACJ,KAAM,IAAIpM,OAAM,+BAGpB,IAAI0N,GAAUlN,EAAU2L,GACpBgB,EAAa,EACbE,KAEAL,GAAsB,EAsEtBW,GAAe,EACflB,GACAK,OAAQ,GAAIlB,IACZQ,YAAaA,EACbC,QAASA,EACTuB,UAAWnL,EACXgL,YAAYhL,EACZ+K,OAAQpB,EAAc,EACtByB,MAAOpL,EACPmK,MAAOnK,EACPxC,MAAOwC,EACPiK,SAAS,EACToB,QAAQ,EACRrJ,KAAM,SAAU8H,EAAM9M,GAClB6M,EAAQC,GAAM,EAAO9M,IAEzBsO,KAAM,WACFtB,EAAEG,MAAQnK,EACVgK,EAAEK,OAAOe,SAEbd,QAAS,SAAUR,EAAM9M,GACrB6M,EAAQC,GAAM,EAAM9M,IAExBuO,OAAQ,SAAUC,GACdxB,EAAEK,OAAOkB,OAAOC,IAEpBhB,QAAS,WAGL,IAAIU,EAAJ,CAIA,IADAA,GAAe,GACRlB,EAAEqB,QAAUX,EAAaV,EAAEL,aAAeK,EAAEK,OAAOvO,QAAO,CAC7D,GAAIyM,MAAYuB,KACZM,EAAIJ,EAAEK,OAAOvO,MACbkO,GAAEJ,UAASQ,EAAIxO,KAAK6P,IAAIrB,EAAGJ,EAAEJ,SACjC,KAAK,GAAI3G,GAAI,EAAGA,EAAImH,EAAGnH,IAAK,CACxB,GAAIuG,GAAOQ,EAAEK,OAAOQ,OACpBtC,GAAMvG,KAAKwH,GACXoB,EAAY5I,KAAKwH,GACjBM,EAAK9H,KAAKwH,EAAKM,MAGnBY,GAAc,EAEU,IAApBV,EAAEK,OAAOvO,QACTkO,EAAEoB,QAGFV,IAAeV,EAAEL,aACjBK,EAAEmB,WAGN,IAAI7M,GAAKsF,EAAS6G,EAAMlC,GACxB0C,GAAQnB,EAAMxL,GAElB4M,GAAe,IAEnBpP,OAAQ,WACJ,MAAOkO,GAAEK,OAAOvO,QAEpBkI,QAAS,WACL,MAAO0G,IAEXE,YAAa,WACT,MAAOA,IAEXV,KAAM,WACF,MAAOF,GAAEK,OAAOvO,OAAS4O,IAAe,GAE5CgB,MAAO,WACH1B,EAAEqB,QAAS,GAEfM,OAAQ,WACA3B,EAAEqB,UAAW,IACjBrB,EAAEqB,QAAS,EACX5N,GAAeuM,EAAEQ,WAGzB,OAAOR,GAgFX,QAAS4B,IAAMlC,EAAQE,GACnB,MAAOH,IAAMC,EAAQ,EAAGE,GA8D5B,QAASiC,IAAO7I,EAAM8I,EAAMzL,EAAUrD,GAClCA,EAAWiD,EAAKjD,GAAYgD,EAC5B,IAAIiF,GAAYlH,EAAUsC,EAC1B0L,IAAa/I,EAAM,SAASgJ,EAAG/I,EAAGjG,GAC9BiI,EAAU6G,EAAME,EAAG,SAAS3O,EAAK8H,GAC7B2G,EAAO3G,EACPnI,EAASK,MAEd,SAASA,GACRL,EAASK,EAAKyO,KA0CtB,QAASG,MACL,GAAIC,GAAa/F,EAASxJ,UAAWoB,EACrC,OAAO,YACH,GAAIrB,GAAOlB,EAAMmB,WACb0B,EAAO9C,KAEP+C,EAAK5B,EAAKA,EAAKZ,OAAS,EACX,mBAANwC,GACP5B,EAAKuM,MAEL3K,EAAK0B,EAGT6L,GAAOK,EAAYxP,EAAM,SAASyP,EAAS7P,EAAIgC,GAC3ChC,EAAGM,MAAMyB,EAAM8N,EAAQ5N,OAAO,SAASlB,GACnC,GAAI+O,GAAW5Q,EAAMmB,UAAW,EAChC2B,GAAGjB,EAAK+O,OAGhB,SAAS/O,EAAK0H,GACVzG,EAAG1B,MAAMyB,GAAOhB,GAAKkB,OAAOwG,OAsMxC,QAASsH,IAASlQ,GAChB,MAAOA,GAGT,QAASmQ,IAAcC,EAAOC,GAC1B,MAAO,UAAStO,EAAQ4G,EAAKzE,EAAU/B,GACnCA,EAAKA,GAAM0B,CACX,IACIyM,GADAC,GAAa,CAEjBxO,GAAO4G,EAAK,SAAS3I,EAAO+I,EAAGlI,GAC3BqD,EAASlE,EAAO,SAASkB,EAAKJ,GACtBI,EACAL,EAASK,GACFkP,EAAMtP,KAAYwP,GACzBC,GAAa,EACbD,EAAaD,GAAU,EAAMrQ,GAC7Ba,EAAS,KAAMiH,KAEfjH,OAGT,SAASK,GACJA,EACAiB,EAAGjB,GAEHiB,EAAG,KAAMoO,EAAaD,EAAaD,GAAU,OAM7D,QAASG,IAAexH,EAAG6G,GACvB,MAAOA,GAsFX,QAASY,IAAY9D,GACjB,MAAO,UAAUxM,GACb,GAAII,GAAOlB,EAAMmB,UAAW,EAC5BD,GAAKsF,KAAK,SAAU3E,GAChB,GAAIX,GAAOlB,EAAMmB,UAAW,EACL,iBAAZkQ,WACHxP,EACIwP,QAAQrP,OACRqP,QAAQrP,MAAMH,GAEXwP,QAAQ/D,IACfzD,EAAU3I,EAAM,SAAUsP,GACtBa,QAAQ/D,GAAMkD,QAK9BjO,EAAUzB,GAAIM,MAAM,KAAMF,IAuDlC,QAASoQ,IAASxQ,EAAIwE,EAAM9D,GAKxB,QAASsG,GAAKjG,GACV,GAAIA,EAAK,MAAOL,GAASK,EACzB,IAAIX,GAAOlB,EAAMmB,UAAW,EAC5BD,GAAKsF,KAAKuK,GACVQ,EAAMnQ,MAAMrB,KAAMmB,GAGtB,QAAS6P,GAAMlP,EAAK2P,GAChB,MAAI3P,GAAYL,EAASK,GACpB2P,MACLC,GAAI3J,GADetG,EAAS,MAbhCA,EAAW4G,EAAS5G,GAAYgD,EAChC,IAAIiN,GAAMlP,EAAUzB,GAChByQ,EAAQhP,EAAU+C,EAetByL,GAAM,MAAM,GA0BhB,QAASW,IAAS7M,EAAUS,EAAM9D,GAC9BA,EAAW4G,EAAS5G,GAAYgD,EAChC,IAAIiF,GAAYlH,EAAUsC,GACtBiD,EAAO,SAASjG,GAChB,GAAIA,EAAK,MAAOL,GAASK,EACzB,IAAIX,GAAOlB,EAAMmB,UAAW,EAC5B,OAAImE,GAAKlE,MAAMrB,KAAMmB,GAAcuI,EAAU3B,OAC7CtG,GAASJ,MAAM,MAAO,MAAM2B,OAAO7B,IAEvCuI,GAAU3B,GAuBd,QAAS6J,IAAQ9M,EAAUS,EAAM9D,GAC7BkQ,GAAS7M,EAAU,WACf,OAAQS,EAAKlE,MAAMrB,KAAMoB,YAC1BK,GAuCP,QAASoQ,IAAOtM,EAAMxE,EAAIU,GAKtB,QAASsG,GAAKjG,GACV,MAAIA,GAAYL,EAASK,OACzB0P,GAAMR,GAGV,QAASA,GAAMlP,EAAK2P,GAChB,MAAI3P,GAAYL,EAASK,GACpB2P,MACLC,GAAI3J,GADetG,EAAS,MAXhCA,EAAW4G,EAAS5G,GAAYgD,EAChC,IAAIiN,GAAMlP,EAAUzB,GAChByQ,EAAQhP,EAAU+C,EAatBiM,GAAMR,GAGV,QAASc,IAAchN,GACnB,MAAO,UAAUlE,EAAOmE,EAAOtD,GAC3B,MAAOqD,GAASlE,EAAOa,IA6D/B,QAASsQ,IAAUtK,EAAM3C,EAAUrD,GAC/B4H,GAAO5B,EAAMqK,GAActP,EAAUsC,IAAYrD,GAuBrD,QAASuQ,IAAYvK,EAAMc,EAAOzD,EAAUrD,GACxC6G,EAAaC,GAAOd,EAAMqK,GAActP,EAAUsC,IAAYrD,GA2DlE,QAASwQ,IAAYlR,GACjB,MAAIqB,GAAQrB,GAAYA,EACjBS,GAAc,SAAUL,EAAMM,GACjC,GAAIyQ,IAAO,CACX/Q,GAAKsF,KAAK,WACN,GAAI0L,GAAY/Q,SACZ8Q,GACAhQ,GAAe,WACXT,EAASJ,MAAM,KAAM8Q,KAGzB1Q,EAASJ,MAAM,KAAM8Q,KAG7BpR,EAAGM,MAAMrB,KAAMmB,GACf+Q,GAAO,IAIf,QAASE,IAAMxI,GACX,OAAQA,EAmFZ,QAASyI,IAAa9L,GACpB,MAAO,UAASa,GACd,MAAiB,OAAVA,EAAiB7D,OAAY6D,EAAOb,IAI/C,QAAS+L,IAAY3P,EAAQ4G,EAAKzE,EAAUrD,GACxC,GAAI8Q,GAAc,GAAI9R,OAAM8I,EAAIhJ,OAChCoC,GAAO4G,EAAK,SAAUkH,EAAG1L,EAAOtD,GAC5BqD,EAAS2L,EAAG,SAAU3O,EAAK8H,GACvB2I,EAAYxN,KAAW6E,EACvBnI,EAASK,MAEd,SAAUA,GACT,GAAIA,EAAK,MAAOL,GAASK,EAEzB,KAAK,GADD0H,MACK9B,EAAI,EAAGA,EAAI6B,EAAIhJ,OAAQmH,IACxB6K,EAAY7K,IAAI8B,EAAQ/C,KAAK8C,EAAI7B,GAEzCjG,GAAS,KAAM+H,KAIvB,QAASgJ,IAAc7P,EAAQ8E,EAAM3C,EAAUrD,GAC3C,GAAI+H,KACJ7G,GAAO8E,EAAM,SAAUgJ,EAAG1L,EAAOtD,GAC7BqD,EAAS2L,EAAG,SAAU3O,EAAK8H,GACnB9H,EACAL,EAASK,IAEL8H,GACAJ,EAAQ/C,MAAM1B,MAAOA,EAAOnE,MAAO6P,IAEvChP,QAGT,SAAUK,GACLA,EACAL,EAASK,GAETL,EAAS,KAAMmJ,EAASpB,EAAQiJ,KAAK,SAAUC,EAAGC,GAC9C,MAAOD,GAAE3N,MAAQ4N,EAAE5N,QACnBsN,GAAa,aAK7B,QAASO,IAAQjQ,EAAQ8E,EAAM3C,EAAUrD,GACrC,GAAIoR,GAASrO,EAAYiD,GAAQ6K,GAAcE,EAC/CK,GAAOlQ,EAAQ8E,EAAMjF,EAAUsC,GAAWrD,GAAYgD,GAqG1D,QAASqO,IAAQ/R,EAAIgS,GAIjB,QAAShL,GAAKjG,GACV,MAAIA,GAAYkG,EAAKlG,OACrBsN,GAAKrH,GALT,GAAIC,GAAOK,EAAS0K,GAAWtO,GAC3B2K,EAAO5M,EAAUyP,GAAYlR,GAMjCgH,KAiKJ,QAASiL,IAAe9K,EAAKK,EAAOzD,EAAUrD,GAC1CA,EAAWiD,EAAKjD,GAAYgD,EAC5B,IAAIwO,MACAvJ,EAAYlH,EAAUsC,EAC1BgE,GAAYZ,EAAKK,EAAO,SAAS2K,EAAK3M,EAAKwB,GACvC2B,EAAUwJ,EAAK3M,EAAK,SAAUzE,EAAKJ,GAC/B,MAAII,GAAYiG,EAAKjG,IACrBmR,EAAO1M,GAAO7E,MACdqG,SAEL,SAAUjG,GACTL,EAASK,EAAKmR,KAwEtB,QAASE,IAAIjL,EAAK3B,GACd,MAAOA,KAAO2B,GAwClB,QAASkL,IAAQrS,EAAIsS,GACjB,GAAI9C,GAAOvM,OAAOsP,OAAO,MACrBC,EAASvP,OAAOsP,OAAO,KAC3BD,GAASA,GAAUvC,EACnB,IAAIY,GAAMlP,EAAUzB,GAChByS,EAAWhS,GAAc,SAAkBL,EAAMM,GACjD,GAAI8E,GAAM8M,EAAOhS,MAAM,KAAMF,EACzBgS,IAAI5C,EAAMhK,GACVrE,GAAe,WACXT,EAASJ,MAAM,KAAMkP,EAAKhK,MAEvB4M,GAAII,EAAQhN,GACnBgN,EAAOhN,GAAKE,KAAKhF,IAEjB8R,EAAOhN,IAAQ9E,GACfiQ,EAAIrQ,MAAM,KAAMF,EAAK6B,OAAO,WACxB,GAAI7B,GAAOlB,EAAMmB,UACjBmP,GAAKhK,GAAOpF,CACZ,IAAIsN,GAAI8E,EAAOhN,SACRgN,GAAOhN,EACd,KAAK,GAAImB,GAAI,EAAGmH,EAAIJ,EAAElO,OAAQmH,EAAImH,EAAGnH,IACjC+G,EAAE/G,GAAGrG,MAAM,KAAMF,QAOjC,OAFAqS,GAASjD,KAAOA,EAChBiD,EAASC,WAAa1S,EACfyS,EA8CX,QAASE,IAAU/Q,EAAQqK,EAAOvL,GAC9BA,EAAWA,GAAYgD,CACvB,IAAI+E,GAAUhF,EAAYwI,QAE1BrK,GAAOqK,EAAO,SAAUoC,EAAM7I,EAAK9E,GAC/Be,EAAU4M,GAAM,SAAUtN,EAAKJ,GACvBN,UAAUb,OAAS,IACnBmB,EAASzB,EAAMmB,UAAW,IAE9BoI,EAAQjD,GAAO7E,EACfD,EAASK,MAEd,SAAUA,GACTL,EAASK,EAAK0H,KAyEtB,QAASmK,IAAc3G,EAAOvL,GAC1BiS,GAAUrK,GAAQ2D,EAAOvL,GAsB7B,QAASmS,IAAgB5G,EAAOzE,EAAO9G,GACnCiS,GAAUpL,EAAaC,GAAQyE,EAAOvL,GA+N1C,QAASoS,IAAK7G,EAAOvL,GAEjB,GADAA,EAAWiD,EAAKjD,GAAYgD,IACvBqB,GAAQkH,GAAQ,MAAOvL,GAAS,GAAIqS,WAAU,wDACnD,KAAK9G,EAAMzM,OAAQ,MAAOkB,IAC1B,KAAK,GAAIiG,GAAI,EAAGmH,EAAI7B,EAAMzM,OAAQmH,EAAImH,EAAGnH,IACrClF,EAAUwK,EAAMtF,IAAIjG,GA0B5B,QAASsS,IAAahK,EAAOwG,EAAMzL,EAAUrD,GACzC,GAAIuS,GAAW/T,EAAM8J,GAAOkK,SAC5B3D,IAAO0D,EAAUzD,EAAMzL,EAAUrD,GA0CrC,QAASyS,IAAQnT,GACb,GAAI2Q,GAAMlP,EAAUzB,EACpB,OAAOS,IAAc,SAAmBL,EAAMgT,GAe1C,MAdAhT,GAAKsF,KAAK,SAAkBxE,EAAOmS,GAC/B,GAAInS,EACAkS,EAAgB,MAAQlS,MAAOA,QAC5B,CACH,GAAIrB,EAEAA,GADAQ,UAAUb,QAAU,EACZ6T,EAEAnU,EAAMmB,UAAW,GAE7B+S,EAAgB,MAAQvT,MAAOA,OAIhC8Q,EAAIrQ,MAAMrB,KAAMmB,KAuE/B,QAASkT,IAAWrH,GAChB,GAAIxD,EASJ,OARI1D,IAAQkH,GACRxD,EAAUoB,EAASoC,EAAOkH,KAE1B1K,KACAY,EAAW4C,EAAO,SAASoC,EAAM7I,GAC7BiD,EAAQjD,GAAO2N,GAAQ9Q,KAAKpD,KAAMoP,MAGnC5F,EAGX,QAAS8K,IAAS3R,EAAQ4G,EAAKzE,EAAUrD,GACrCmR,GAAQjQ,EAAQ4G,EAAK,SAAS3I,EAAOmC,GACjC+B,EAASlE,EAAO,SAASkB,EAAK8H,GAC1B7G,EAAGjB,GAAM8H,MAEdnI,GA2FP,QAAS8S,IAAW3T,GAClB,MAAO,YACL,MAAOA,IAwFX,QAAS4T,IAAMC,EAAMrF,EAAM3N,GASvB,QAASiT,GAAWC,EAAKC,GACrB,GAAiB,gBAANA,GACPD,EAAIE,OAASD,EAAEC,OAASC,EAExBH,EAAII,aAAqC,kBAAfH,GAAEI,SACxBJ,EAAEI,SACFT,IAAYK,EAAEI,UAAYC,GAE9BN,EAAIO,YAAcN,EAAEM,gBACjB,CAAA,GAAiB,gBAANN,IAA+B,gBAANA,GAGvC,KAAM,IAAI5S,OAAM,oCAFhB2S,GAAIE,OAASD,GAAKE,GAqB1B,QAASK,KACLC,EAAM,SAAStT,GACPA,GAAOuT,IAAYC,EAAQT,QACI,kBAAvBS,GAAQJ,aACZI,EAAQJ,YAAYpT,IACxBd,WAAWmU,EAAcG,EAAQP,aAAaM,IAE9C5T,EAASJ,MAAM,KAAMD,aA9CjC,GAAI0T,GAAgB,EAChBG,EAAmB,EAEnBK,GACAT,MAAOC,EACPC,aAAcR,GAAWU,GA2B7B,IARI7T,UAAUb,OAAS,GAAqB,kBAATkU,IAC/BhT,EAAW2N,GAAQ3K,EACnB2K,EAAOqF,IAEPC,EAAWY,EAASb,GACpBhT,EAAWA,GAAYgD,GAGP,kBAAT2K,GACP,KAAM,IAAIpN,OAAM,oCAGpB,IAAIoT,GAAQ5S,EAAU4M,GAElBiG,EAAU,CAadF,KAgHJ,QAASI,IAAOvI,EAAOvL,GACnBiS,GAAUlD,GAAcxD,EAAOvL,GA+HnC,QAAS+T,IAAQ/N,EAAM3C,EAAUrD,GAY7B,QAASgU,GAAWC,EAAMC,GACtB,GAAIjD,GAAIgD,EAAKE,SAAUjD,EAAIgD,EAAMC,QACjC,OAAOlD,GAAIC,GAAI,EAAKD,EAAIC,EAAI,EAAI,EAbpC,GAAIjJ,GAAYlH,EAAUsC,EAC1B+H,IAAIpF,EAAM,SAAUgJ,EAAGhP,GACnBiI,EAAU+G,EAAG,SAAU3O,EAAK8T,GACxB,MAAI9T,GAAYL,EAASK,OACzBL,GAAS,MAAOb,MAAO6P,EAAGmF,SAAUA,OAEzC,SAAU9T,EAAK0H,GACd,MAAI1H,GAAYL,EAASK,OACzBL,GAAS,KAAMmJ,EAASpB,EAAQiJ,KAAKgD,GAAapD,GAAa,aAkDvE,QAASwD,IAAQpT,EAASqT,EAAcC,GACpC,GAAIhV,GAAKyB,EAAUC,EAEnB,OAAOjB,IAAc,SAAUL,EAAMM,GAIjC,QAASuU,KACL,GAAIzI,GAAO9K,EAAQ8K,MAAQ,YACvBtL,EAAS,GAAID,OAAM,sBAAwBuL,EAAO,eACtDtL,GAAMgU,KAAO,YACTF,IACA9T,EAAM8T,KAAOA,GAEjBG,GAAW,EACXzU,EAASQ,GAXb,GACIkU,GADAD,GAAW,CAcf/U,GAAKsF,KAAK,WACDyP,IACDzU,EAASJ,MAAM,KAAMD,WACrBgV,aAAaD,MAKrBA,EAAQnV,WAAWgV,EAAiBF,GACpC/U,EAAGM,MAAM,KAAMF,KAmBvB,QAASkV,IAAUlW,EAAOgL,EAAKmL,EAAMrM,GAKnC,IAJA,GAAIlF,IAAQ,EACRxE,EAASgW,GAAUC,IAAYrL,EAAMhL,IAAUmW,GAAQ,IAAK,GAC5D5U,EAASjB,MAAMF,GAEZA,KACLmB,EAAOuI,EAAY1J,IAAWwE,GAAS5E,EACvCA,GAASmW,CAEX,OAAO5U,GAmBT,QAAS+U,IAAUC,EAAOnO,EAAOzD,EAAUrD,GACvC,GAAIiI,GAAYlH,EAAUsC,EAC1B6R,IAASN,GAAU,EAAGK,EAAO,GAAInO,EAAOmB,EAAWjI,GA+FvD,QAASwF,IAAWQ,EAAMmP,EAAa9R,EAAUrD,GACzCL,UAAUb,QAAU,IACpBkB,EAAWqD,EACXA,EAAW8R,EACXA,EAAc9Q,GAAQ2B,UAE1BhG,EAAWiD,EAAKjD,GAAYgD,EAC5B,IAAIiF,GAAYlH,EAAUsC,EAE1BuE,IAAO5B,EAAM,SAASmC,EAAGiN,EAAG9T,GACxB2G,EAAUkN,EAAahN,EAAGiN,EAAG9T,IAC9B,SAASjB,GACRL,EAASK,EAAK8U,KAyCtB,QAASE,IAAQ9J,EAAOvL,GACpB,GACIC,GADAO,EAAQ,IAEZR,GAAWA,GAAYgD,EACvBsS,GAAW/J,EAAO,SAASoC,EAAM3N,GAC7Be,EAAU4M,GAAM,SAAUtN,EAAKkV,GAEvBtV,EADAN,UAAUb,OAAS,EACVN,EAAMmB,UAAW,GAEjB4V,EAEb/U,EAAQH,EACRL,GAAUK,MAEf,WACCL,EAASQ,EAAOP,KAiBxB,QAASuV,IAAUlW,GACf,MAAO,YACH,OAAQA,EAAG0S,YAAc1S,GAAIM,MAAM,KAAMD,YAsCjD,QAAS8V,IAAO3R,EAAMT,EAAUrD,GAC5BA,EAAW4G,EAAS5G,GAAYgD,EAChC,IAAIiF,GAAYlH,EAAUsC,EAC1B,KAAKS,IAAQ,MAAO9D,GAAS,KAC7B,IAAIsG,GAAO,SAASjG,GAChB,GAAIA,EAAK,MAAOL,GAASK,EACzB,IAAIyD,IAAQ,MAAOmE,GAAU3B,EAC7B,IAAI5G,GAAOlB,EAAMmB,UAAW,EAC5BK,GAASJ,MAAM,MAAO,MAAM2B,OAAO7B,IAEvCuI,GAAU3B,GAyBd,QAASoP,IAAM5R,EAAMT,EAAUrD,GAC3ByV,GAAO,WACH,OAAQ3R,EAAKlE,MAAMrB,KAAMoB,YAC1B0D,EAAUrD,GA3jKjB,GA8DI2V,IA9DA/V,GAAQ,SAASN,GACjB,GAAII,GAAOlB,EAAMmB,UAAW,EAC5B,OAAO,YACH,GAAIiW,GAAWpX,EAAMmB,UACrB,OAAOL,GAAGM,MAAM,KAAMF,EAAK6B,OAAOqU,MAItC7V,GAAgB,SAAUT,GAC1B,MAAO,YACH,GAAII,GAAOlB,EAAMmB,WACbK,EAAWN,EAAKuM,KACpB3M,GAAGqC,KAAKpD,KAAMmB,EAAMM,KAkCxB6V,GAA0C,kBAAjBC,eAA+BA,aACxDC,GAAiC,gBAAZvI,UAAoD,kBAArBA,SAAQwI,QAkB5DL,IADAE,GACSC,aACFC,GACEvI,QAAQwI,SAER3W,CAGb,IAAIoB,IAAiBjB,EAAKmW,IA2FtB/U,GAAmC,kBAAXC,QA6BxBoV,GAA8B,gBAAVjY,SAAsBA,QAAUA,OAAOuE,SAAWA,QAAUvE,OAGhFkY,GAA0B,gBAARC,OAAoBA,MAAQA,KAAK5T,SAAWA,QAAU4T,KAGxEC,GAAOH,IAAcC,IAAYG,SAAS,iBAG1CC,GAAWF,GAAKvV,OAGhB0V,GAAchU,OAAO8C,UAGrB3D,GAAiB6U,GAAY7U,eAO7BM,GAAuBuU,GAAY9L,SAGnC7I,GAAmB0U,GAAWA,GAASxV,YAAcgB,OA8BrD0U,GAAgBjU,OAAO8C,UAOvBnD,GAAyBsU,GAAc/L,SAcvCpI,GAAU,gBACVD,GAAe,qBAGfE,GAAiBgU,GAAWA,GAASxV,YAAcgB,OAmBnDa,GAAW,yBACXF,GAAU,oBACVC,GAAS,6BACTE,GAAW,iBA8BXE,GAAmB,iBAgEnBmE,MA2BAwP,GAAmC,kBAAX5V,SAAyBA,OAAOuF,SAExDO,GAAc,SAAUX,GACxB,MAAOyQ,KAAkBzQ,EAAKyQ,KAAmBzQ,EAAKyQ,OAmDtDhT,GAAU,qBAcViT,GAAgBnU,OAAO8C,UAGvBsR,GAAmBD,GAAchV,eAGjCkV,GAAuBF,GAAcE,qBAoBrCrS,GAAcf,EAAgB,WAAa,MAAO7D,eAAkB6D,EAAkB,SAASrE,GACjG,MAAOoE,GAAapE,IAAUwX,GAAiBhV,KAAKxC,EAAO,YACxDyX,GAAqBjV,KAAKxC,EAAO,WA0BlCkF,GAAUrF,MAAMqF,QAoBhBwS,GAAgC,gBAAX3Y,IAAuBA,IAAYA,EAAQ4Y,UAAY5Y,EAG5E6Y,GAAaF,IAAgC,gBAAV1Y,SAAsBA,SAAWA,OAAO2Y,UAAY3Y,OAGvF6Y,GAAgBD,IAAcA,GAAW7Y,UAAY2Y,GAGrDI,GAASD,GAAgBZ,GAAKa,OAASnV,OAGvCoV,GAAiBD,GAASA,GAAOxS,SAAW3C,OAmB5C2C,GAAWyS,IAAkBxT,EAG7BE,GAAqB,iBAGrBC,GAAW,mBAkBXsT,GAAY,qBACZC,GAAW,iBACXC,GAAU,mBACVC,GAAU,gBACVC,GAAW,iBACXC,GAAY,oBACZC,GAAS,eACTC,GAAY,kBACZC,GAAY,kBACZC,GAAY,kBACZC,GAAS,eACTC,GAAY,kBACZC,GAAa,mBAEbC,GAAiB,uBACjBC,GAAc,oBACdC,GAAa,wBACbC,GAAa,wBACbC,GAAU,qBACVC,GAAW,sBACXC,GAAW,sBACXC,GAAW,sBACXC,GAAkB,6BAClBC,GAAY,uBACZC,GAAY,uBAGZ1U,KACJA,IAAekU,IAAclU,GAAemU,IAC5CnU,GAAeoU,IAAWpU,GAAeqU,IACzCrU,GAAesU,IAAYtU,GAAeuU,IAC1CvU,GAAewU,IAAmBxU,GAAeyU,IACjDzU,GAAe0U,KAAa,EAC5B1U,GAAemT,IAAanT,GAAeoT,IAC3CpT,GAAegU,IAAkBhU,GAAeqT,IAChDrT,GAAeiU,IAAejU,GAAesT,IAC7CtT,GAAeuT,IAAYvT,GAAewT,IAC1CxT,GAAeyT,IAAUzT,GAAe0T,IACxC1T,GAAe2T,IAAa3T,GAAe4T,IAC3C5T,GAAe6T,IAAU7T,GAAe8T,IACxC9T,GAAe+T,KAAc,CA4B7B,IAAIY,IAAkC,gBAAXza,IAAuBA,IAAYA,EAAQ4Y,UAAY5Y,EAG9E0a,GAAeD,IAAkC,gBAAVxa,SAAsBA,SAAWA,OAAO2Y,UAAY3Y,OAG3F0a,GAAkBD,IAAgBA,GAAa1a,UAAYya,GAG3DG,GAAcD,IAAmB5C,GAAWzI,QAG5CuL,GAAY,WACd,IACE,MAAOD,KAAeA,GAAYE,SAAWF,GAAYE,QAAQ,QACjE,MAAO9Y,QAIP+Y,GAAmBF,IAAYA,GAASpU,aAmBxCA,GAAesU,GAAmBhV,EAAUgV,IAAoBlV,EAGhEmV,GAAgB3W,OAAO8C,UAGvBN,GAAmBmU,GAAcxX,eAsCjC4D,GAAgB/C,OAAO8C,UA+BvBO,GAAaL,EAAQhD,OAAOuD,KAAMvD,QAGlC4W,GAAgB5W,OAAO8C,UAGvBQ,GAAmBsT,GAAczX,eAuMjC0X,GAAgB9R,EAAQD,EAAagS,EAAAA,GAyCrCzR,GAAS,SAAS5B,EAAM3C,EAAUrD,GAClC,GAAIsZ,GAAuBvW,EAAYiD,GAAQwB,EAAkB4R,EACjEE,GAAqBtT,EAAMjF,EAAUsC,GAAWrD,IA+DhDoL,GAAMzD,EAAWE,GAmCjB0R,GAAYtY,EAAYmK,IA2BxB8J,GAAW9M,EAAgBP,GAoB3B2R,GAAYlS,EAAQ4N,GAAU,GAqB9BuE,GAAkBxY,EAAYuY,IA0D9B5Q,GAAUL,IAoKV2D,GAAO,SAAUX,EAAOoB,EAAa3M,GAiErC,QAAS0Z,GAAY5U,EAAK6I,GACtBgM,EAAW3U,KAAK,WACZ4U,EAAQ9U,EAAK6I,KAIrB,QAASkM,KACL,GAA0B,IAAtBF,EAAW7a,QAAiC,IAAjBgb,EAC3B,MAAO9Z,GAAS,KAAM+H,EAE1B,MAAM4R,EAAW7a,QAAUgb,EAAenN,GAAa,CACnD,GAAIoN,GAAMJ,EAAW9L,OACrBkM,MAKR,QAASC,GAAYC,EAAU3a,GAC3B,GAAI4a,GAAgBC,EAAUF,EACzBC,KACDA,EAAgBC,EAAUF,OAG9BC,EAAclV,KAAK1F,GAGvB,QAAS8a,GAAaH,GAClB,GAAIC,GAAgBC,EAAUF,MAC9B5R,GAAU6R,EAAe,SAAU5a,GAC/BA,MAEJua,IAIJ,QAASD,GAAQ9U,EAAK6I,GAClB,IAAI0M,EAAJ,CAEA,GAAIC,GAAe1T,EAAS,SAASvG,EAAKJ,GAKtC,GAJA6Z,IACIna,UAAUb,OAAS,IACnBmB,EAASzB,EAAMmB,UAAW,IAE1BU,EAAK,CACL,GAAIka,KACJ5R,GAAWZ,EAAS,SAAS0J,EAAK+I,GAC9BD,EAAYC,GAAQ/I,IAExB8I,EAAYzV,GAAO7E,EACnBoa,GAAW,EACXF,EAAY5X,OAAOsP,OAAO,MAE1B7R,EAASK,EAAKka,OAEdxS,GAAQjD,GAAO7E,EACfma,EAAatV,IAIrBgV,IACA,IAAIrO,GAAS1K,EAAU4M,EAAKA,EAAK7O,OAAS,GACtC6O,GAAK7O,OAAS,EACd2M,EAAO1D,EAASuS,GAEhB7O,EAAO6O,IAIf,QAASG,KAML,IAFA,GAAIC,GACA1S,EAAU,EACP2S,EAAa7b,QAChB4b,EAAcC,EAAa1O,MAC3BjE,IACAK,EAAUuS,EAAcF,GAAc,SAAUG,GACD,MAArCC,EAAsBD,IACxBF,EAAa3V,KAAK6V,IAK9B,IAAI7S,IAAY+S,EACZ,KAAM,IAAIxa,OACN,iEAKZ,QAASqa,GAAcX,GACnB,GAAIha,KAMJ,OALA0I,GAAW4C,EAAO,SAAUoC,EAAM7I,GAC1BT,GAAQsJ,IAASzE,EAAYyE,EAAMsM,EAAU,IAAM,GACnDha,EAAO+E,KAAKF,KAGb7E,EAlKgB,kBAAhB0M,KAEP3M,EAAW2M,EACXA,EAAc,MAElB3M,EAAWiD,EAAKjD,GAAYgD,EAC5B,IAAIgY,GAAUlV,EAAKyF,GACfwP,EAAWC,EAAQlc,MACvB,KAAKic,EACD,MAAO/a,GAAS,KAEf2M,KACDA,EAAcoO,EAGlB,IAAIhT,MACA+R,EAAe,EACfO,GAAW,EAEXF,EAAY5X,OAAOsP,OAAO,MAE1B8H,KAGAgB,KAEAG,IAEJnS,GAAW4C,EAAO,SAAUoC,EAAM7I,GAC9B,IAAKT,GAAQsJ,GAIT,MAFA+L,GAAY5U,GAAM6I,QAClBgN,GAAa3V,KAAKF,EAItB,IAAImW,GAAetN,EAAKnP,MAAM,EAAGmP,EAAK7O,OAAS,GAC3Coc,EAAwBD,EAAanc,MACzC,OAA8B,KAA1Boc,GACAxB,EAAY5U,EAAK6I,OACjBgN,GAAa3V,KAAKF,KAGtBgW,EAAsBhW,GAAOoW,MAE7B7S,GAAU4S,EAAc,SAAUE,GAC9B,IAAK5P,EAAM4P,GACP,KAAM,IAAI5a,OAAM,oBAAsBuE,EAClC,oCACAqW,EAAiB,QACjBF,EAAalQ,KAAK,MAE1BiP,GAAYmB,EAAgB,WACxBD,IAC8B,IAA1BA,GACAxB,EAAY5U,EAAK6I,UAMjC8M,IACAZ,KA6HAxQ,GAAY,kBAyBZG,GAAW,EAAI,EAGf4R,GAAc9E,GAAWA,GAASjR,UAAYvD,OAC9CyH,GAAiB6R,GAAcA,GAAY3Q,SAAW3I,OAoHtDuZ,GAAgB,kBAChBC,GAAoB,kBACpBC,GAAwB,kBACxBC,GAAsB,kBACtBC,GAAeH,GAAoBC,GAAwBC,GAC3DE,GAAa,iBAGbC,GAAQ,UAGRvR,GAAewR,OAAO,IAAMD,GAAQN,GAAiBI,GAAeC,GAAa,KAcjFG,GAAkB,kBAClBC,GAAsB,kBACtBC,GAA0B,kBAC1BC,GAAwB,kBACxBC,GAAiBH,GAAsBC,GAA0BC,GACjEE,GAAe,iBAGfC,GAAW,IAAMN,GAAkB,IACnCO,GAAU,IAAMH,GAAiB,IACjCI,GAAS,2BACTC,GAAa,MAAQF,GAAU,IAAMC,GAAS,IAC9CE,GAAc,KAAOV,GAAkB,IACvCW,GAAa,kCACbC,GAAa,qCACbC,GAAU,UAGVC,GAAWL,GAAa,IACxBM,GAAW,IAAMV,GAAe,KAChCW,GAAY,MAAQH,GAAU,OAASH,GAAaC,GAAYC,IAAY1R,KAAK,KAAO,IAAM6R,GAAWD,GAAW,KACpHG,GAAQF,GAAWD,GAAWE,GAC9BE,GAAW,OAASR,GAAcH,GAAU,IAAKA,GAASI,GAAYC,GAAYN,IAAUpR,KAAK,KAAO,IAGxGR,GAAYqR,OAAOS,GAAS,MAAQA,GAAS,KAAOU,GAAWD,GAAO,KAoDtEhS,GAAS,aAwCTI,GAAU,qDACVC,GAAe,IACfE,GAAS,eACTJ,GAAiB,kCAsJrBkB,IAAI9G,UAAU2X,WAAa,SAASxQ,GAQhC,MAPIA,GAAKyQ,KAAMzQ,EAAKyQ,KAAK3W,KAAOkG,EAAKlG,KAChC/H,KAAK6N,KAAOI,EAAKlG,KAClBkG,EAAKlG,KAAMkG,EAAKlG,KAAK2W,KAAOzQ,EAAKyQ,KAChC1e,KAAK8N,KAAOG,EAAKyQ,KAEtBzQ,EAAKyQ,KAAOzQ,EAAKlG,KAAO,KACxB/H,KAAKO,QAAU,EACR0N,GAGXL,GAAI9G,UAAU+I,MAAQ,WAClB,KAAM7P,KAAK6N,MAAM7N,KAAKsP,OACtB,OAAOtP,OAGX4N,GAAI9G,UAAU6X,YAAc,SAAS1Q,EAAM2Q,GACvCA,EAAQF,KAAOzQ,EACf2Q,EAAQ7W,KAAOkG,EAAKlG,KAChBkG,EAAKlG,KAAMkG,EAAKlG,KAAK2W,KAAOE,EAC3B5e,KAAK8N,KAAO8Q,EACjB3Q,EAAKlG,KAAO6W,EACZ5e,KAAKO,QAAU,GAGnBqN,GAAI9G,UAAU+X,aAAe,SAAS5Q,EAAM2Q,GACxCA,EAAQF,KAAOzQ,EAAKyQ,KACpBE,EAAQ7W,KAAOkG,EACXA,EAAKyQ,KAAMzQ,EAAKyQ,KAAK3W,KAAO6W,EAC3B5e,KAAK6N,KAAO+Q,EACjB3Q,EAAKyQ,KAAOE,EACZ5e,KAAKO,QAAU,GAGnBqN,GAAI9G,UAAUiI,QAAU,SAASd,GACzBjO,KAAK6N,KAAM7N,KAAK6e,aAAa7e,KAAK6N,KAAMI,GACvCF,GAAW/N,KAAMiO,IAG1BL,GAAI9G,UAAUL,KAAO,SAASwH,GACtBjO,KAAK8N,KAAM9N,KAAK2e,YAAY3e,KAAK8N,KAAMG,GACtCF,GAAW/N,KAAMiO,IAG1BL,GAAI9G,UAAUwI,MAAQ,WAClB,MAAOtP,MAAK6N,MAAQ7N,KAAKye,WAAWze,KAAK6N,OAG7CD,GAAI9G,UAAU4G,IAAM,WAChB,MAAO1N,MAAK8N,MAAQ9N,KAAKye,WAAWze,KAAK8N,OAG7CF,GAAI9G,UAAUgY,QAAU,WAGpB,IAAI,GAFAvV,GAAM9I,MAAMT,KAAKO,QACjBwe,EAAO/e,KAAK6N,KACRnN,EAAM,EAAGA,EAAMV,KAAKO,OAAQG,IAChC6I,EAAI7I,GAAOqe,EAAKxQ,KAChBwQ,EAAOA,EAAKhX,IAEhB,OAAOwB,IAGXqE,GAAI9G,UAAUkJ,OAAS,SAAUC,GAE7B,IADA,GAAI8O,GAAO/e,KAAK6N,KACRkR,GAAM,CACV,GAAIhX,GAAOgX,EAAKhX,IACZkI,GAAO8O,IACP/e,KAAKye,WAAWM,GAEpBA,EAAOhX,EAEX,MAAO/H,MA0QX,IAi3CIgf,IAj3CAxO,GAAezH,EAAQD,EAAa,GAyJpCmW,GAAU,WACV,MAAOvO,IAAIrP,MAAM,KAAMpB,EAAMmB,WAAW6S,YAGxCiL,GAAUze,MAAMqG,UAAU9D,OAoB1Bmc,GAAc,SAAS1X,EAAMc,EAAOzD,EAAUrD,GAC9CA,EAAWA,GAAYgD,CACvB,IAAIiF,GAAYlH,EAAUsC,EAC1B6R,IAASlP,EAAMc,EAAO,SAAS2K,EAAKzR,GAChCiI,EAAUwJ,EAAK,SAASpR,GACpB,MAAIA,GAAYL,EAASK,GAClBL,EAAS,KAAMxB,EAAMmB,UAAW,OAE5C,SAASU,EAAKsd,GAEb,IAAK,GADD1d,MACKgG,EAAI,EAAGA,EAAI0X,EAAW7e,OAAQmH,IAC/B0X,EAAW1X,KACXhG,EAASwd,GAAQ7d,MAAMK,EAAQ0d,EAAW1X,IAIlD,OAAOjG,GAASK,EAAKJ,MA6BzBsB,GAAS+F,EAAQoW,GAAarE,EAAAA,GAoB9BuE,GAAetW,EAAQoW,GAAa,GA4CpCG,GAAW,WACX,GAAIC,GAAStf,EAAMmB,WACfD,GAAQ,MAAM6B,OAAOuc,EACzB,OAAO,YACH,GAAI9d,GAAWL,UAAUA,UAAUb,OAAS,EAC5C,OAAOkB,GAASJ,MAAMrB,KAAMmB,KA0FhCqe,GAASpW,EAAW2H,GAAcD,GAAUM,KAwB5CqO,GAAc5V,EAAgBkH,GAAcD,GAAUM,KAsBtDsO,GAAe3W,EAAQ0W,GAAa,GAoDpCE,GAAMtO,GAAY,OA6QlB0F,GAAahO,EAAQiJ,GAAa,GAwFlC4N,GAAQxW,EAAW2H,GAAcqB,GAAOA,KAsBxCyN,GAAahW,EAAgBkH,GAAcqB,GAAOA,KAqBlD0N,GAAc/W,EAAQ8W,GAAY,GAwFlChN,GAASzJ,EAAWwJ,IAqBpBmN,GAAclW,EAAgB+I,IAmB9BoN,GAAejX,EAAQgX,GAAa,GA6DpCE,GAAe,SAASxY,EAAMc,EAAOzD,EAAUrD,GAC/CA,EAAWA,GAAYgD,CACvB,IAAIiF,GAAYlH,EAAUsC,EAC1B6R,IAASlP,EAAMc,EAAO,SAAS2K,EAAKzR,GAChCiI,EAAUwJ,EAAK,SAASpR,EAAKyE,GACzB,MAAIzE,GAAYL,EAASK,GAClBL,EAAS,MAAO8E,IAAKA,EAAK2M,IAAKA,OAE3C,SAASpR,EAAKsd,GAKb,IAAK,GAJD1d,MAEAyB,EAAiBa,OAAO8C,UAAU3D,eAE7BuE,EAAI,EAAGA,EAAI0X,EAAW7e,OAAQmH,IACnC,GAAI0X,EAAW1X,GAAI,CACf,GAAInB,GAAM6Y,EAAW1X,GAAGnB,IACpB2M,EAAMkM,EAAW1X,GAAGwL,GAEpB/P,GAAeC,KAAK1B,EAAQ6E,GAC5B7E,EAAO6E,GAAKE,KAAKyM,GAEjBxR,EAAO6E,IAAQ2M,GAK3B,MAAOzR,GAASK,EAAKJ,MAwCzBwe,GAAUnX,EAAQkX,GAAcnF,EAAAA,GAqBhCqF,GAAgBpX,EAAQkX,GAAc,GA6BtCG,GAAM/O,GAAY,OAmFlBgP,GAAYtX,EAAQiK,GAAgB8H,EAAAA,GAqBpCwF,GAAkBvX,EAAQiK,GAAgB,EA4G1CgM,IADAxH,GACWvI,QAAQwI,SACZH,GACIC,aAEAzW,CAGf,IAAI2W,IAAWxW,EAAK+d,IA4NhBuB,GAAU,SAAUpS,EAAQC,GAC5B,GAAIsB,GAAUlN,EAAU2L,EACxB,OAAOD,IAAM,SAAUsS,EAAOzd,GAC1B2M,EAAQ8Q,EAAM,GAAIzd,IACnBqL,EAAa,IA0BhBqS,GAAgB,SAAStS,EAAQC,GAEjC,GAAIK,GAAI8R,GAAQpS,EAAQC,EA4CxB,OAzCAK,GAAEhI,KAAO,SAAS8H,EAAMmS,EAAUjf,GAE9B,GADgB,MAAZA,IAAkBA,EAAWgD,GACT,kBAAbhD,GACP,KAAM,IAAIO,OAAM,mCAMpB,IAJAyM,EAAEC,SAAU,EACP5I,GAAQyI,KACTA,GAAQA,IAEQ,IAAhBA,EAAKhO,OAEL,MAAO2B,IAAe,WAClBuM,EAAEG,SAIV8R,GAAWA,GAAY,CAEvB,KADA,GAAIC,GAAWlS,EAAEK,OAAOjB,KACjB8S,GAAYD,GAAYC,EAASD,UACpCC,EAAWA,EAAS5Y,IAGxB,KAAK,GAAIL,GAAI,EAAGmH,EAAIN,EAAKhO,OAAQmH,EAAImH,EAAGnH,IAAK,CACzC,GAAII,IACAyG,KAAMA,EAAK7G,GACXgZ,SAAUA,EACVjf,SAAUA,EAGVkf,GACAlS,EAAEK,OAAO+P,aAAa8B,EAAU7Y,GAEhC2G,EAAEK,OAAOrI,KAAKqB,GAGtB5F,GAAeuM,EAAEQ,gBAIdR,GAAEM,QAEFN,GA0PPmS,GAASxX,EAAWkL,IAqBpBuM,GAAchX,EAAgByK,IAmB9BwM,GAAe/X,EAAQ8X,GAAa,GAkMpCE,GAAY,SAAUtM,EAAMrF,GACvBA,IACDA,EAAOqF,EACPA,EAAO,KAEX,IAAIW,GAAQ5S,EAAU4M,EACtB,OAAO5N,IAAc,SAAUL,EAAMM,GACjC,QAASyL,GAAOnK,GACZqS,EAAM/T,MAAM,KAAMF,EAAK6B,OAAOD,IAG9B0R,EAAMD,GAAMC,EAAMvH,EAAQzL,GACzB+S,GAAMtH,EAAQzL,MAuGvBuf,GAAO5X,EAAW2H,GAAckQ,QAASnQ,KAuBzCoQ,GAAYrX,EAAgBkH,GAAckQ,QAASnQ,KAsBnDqQ,GAAapY,EAAQmY,GAAW,GA4IhC1K,GAAanW,KAAK+gB,KAClB7K,GAAYlW,KAAKC,IA8EjBuU,GAAQ9L,EAAQ0N,GAAWqE,EAAAA,GAgB3BuG,GAActY,EAAQ0N,GAAW,GA2QjC6K,GAAY,SAAStU,EAAOvL,GAM5B,QAAS8f,GAASpgB,GACd,GAAIiO,GAAO5M,EAAUwK,EAAMwU,KAC3BrgB,GAAKsF,KAAK4B,EAASN,IACnBqH,EAAK/N,MAAM,KAAMF,GAGrB,QAAS4G,GAAKjG,GACV,MAAIA,IAAO0f,IAAcxU,EAAMzM,OACpBkB,EAASJ,MAAM,KAAMD,eAEhCmgB,GAASthB,EAAMmB,UAAW,IAd9B,GADAK,EAAWiD,EAAKjD,GAAYgD,IACvBqB,GAAQkH,GAAQ,MAAOvL,GAAS,GAAIO,OAAM,6DAC/C,KAAKgL,EAAMzM,OAAQ,MAAOkB,IAC1B,IAAI+f,GAAY,CAehBD,QAoEAxc,IACA1D,MAAOA,GACP2Z,UAAWA,GACXE,gBAAiBA,GACjB5Z,SAAUA,EACVqM,KAAMA,GACNZ,WAAYA,GACZsD,MAAOA,GACP4O,QAASA,GACTjc,OAAQA,GACRmc,YAAaA,GACbE,aAAcA,GACdC,SAAUA,GACVE,OAAQA,GACRC,YAAaA,GACbC,aAAcA,GACdC,IAAKA,GACLpO,SAAUA,GACVK,QAASA,GACTD,SAAUA,GACVE,OAAQA,GACR4P,KAAM1P,GACNA,UAAWC,GACX3I,OAAQA,GACRP,YAAaA,EACb0H,aAAcA,GACduG,WAAYA,GACZ9E,YAAaA,GACb2N,MAAOA,GACPC,WAAYA,GACZC,YAAaA,GACbjN,OAAQA,GACRkN,YAAaA,GACbC,aAAcA,GACdlN,QAASA,GACToN,QAASA,GACTD,aAAcA,GACdE,cAAeA,GACfC,IAAKA,GACLvT,IAAKA,GACL8J,SAAUA,GACVsE,UAAWA,GACXoF,UAAWA,GACXrN,eAAgBA,GAChBsN,gBAAiBA,GACjBlN,QAASA,GACTqE,SAAUA,GACViK,SAAU/N,GACVA,cAAeC,GACf6M,cAAeA,GACfvS,MAAOqS,GACP1M,KAAMA,GACNvD,OAAQA,GACRyD,YAAaA,GACbG,QAASA,GACTG,WAAYA,GACZuM,OAAQA,GACRC,YAAaA,GACbC,aAAcA,GACdtM,MAAOA,GACPuM,UAAWA,GACXrQ,IAAKA,GACL6E,OAAQA,GACRgC,aAAcrV,GACd8e,KAAMA,GACNE,UAAWA,GACXC,WAAYA,GACZ3L,OAAQA,GACRK,QAASA,GACThB,MAAOA,GACP8M,WAAYlL,GACZ4K,YAAaA,GACbpa,UAAWA,GACX6P,QAASA,GACTG,UAAWA,GACXE,MAAOA,GACPmK,UAAWA,GACXpK,OAAQA,GAGR0K,IAAKhC,GACLiC,SAAUhC,GACViC,UAAWhC,GACXiC,IAAKf,GACLgB,SAAUd,GACVe,UAAWd,GACXe,KAAM1C,GACN2C,UAAW1C,GACX2C,WAAY1C,GACZ2C,QAAStQ,GACTuQ,cAAevL,GACfwL,aAAcvQ,GACdwQ,UAAWnZ,GACXoZ,gBAAiBjS,GACjBkS,eAAgB5Z,EAChB6Z,OAAQrS,GACRsS,MAAOtS,GACPuS,MAAO9O,GACP+O,OAAQjQ,GACRkQ,YAAahD,GACbiD,aAAchD,GACdiD,SAAU3hB,EAGd3B,GAAiB,QAAIoF,GACrBpF,EAAQ0B,MAAQA,GAChB1B,EAAQqb,UAAYA,GACpBrb,EAAQub,gBAAkBA,GAC1Bvb,EAAQ2B,SAAWA,EACnB3B,EAAQgO,KAAOA,GACfhO,EAAQoN,WAAaA,GACrBpN,EAAQ0Q,MAAQA,GAChB1Q,EAAQsf,QAAUA,GAClBtf,EAAQqD,OAASA,GACjBrD,EAAQwf,YAAcA,GACtBxf,EAAQ0f,aAAeA,GACvB1f,EAAQ2f,SAAWA,GACnB3f,EAAQ6f,OAASA,GACjB7f,EAAQ8f,YAAcA,GACtB9f,EAAQ+f,aAAeA,GACvB/f,EAAQggB,IAAMA,GACdhgB,EAAQ4R,SAAWA,GACnB5R,EAAQiS,QAAUA,GAClBjS,EAAQgS,SAAWA,GACnBhS,EAAQkS,OAASA,GACjBlS,EAAQ8hB,KAAO1P,GACfpS,EAAQoS,UAAYC,GACpBrS,EAAQ0J,OAASA,GACjB1J,EAAQmJ,YAAcA,EACtBnJ,EAAQ6Q,aAAeA,GACvB7Q,EAAQoX,WAAaA,GACrBpX,EAAQsS,YAAcA,GACtBtS,EAAQigB,MAAQA,GAChBjgB,EAAQkgB,WAAaA,GACrBlgB,EAAQmgB,YAAcA,GACtBngB,EAAQkT,OAASA,GACjBlT,EAAQogB,YAAcA,GACtBpgB,EAAQqgB,aAAeA,GACvBrgB,EAAQmT,QAAUA,GAClBnT,EAAQugB,QAAUA,GAClBvgB,EAAQsgB,aAAeA,GACvBtgB,EAAQwgB,cAAgBA,GACxBxgB,EAAQygB,IAAMA,GACdzgB,EAAQkN,IAAMA,GACdlN,EAAQgX,SAAWA,GACnBhX,EAAQsb,UAAYA,GACpBtb,EAAQ0gB,UAAYA,GACpB1gB,EAAQqT,eAAiBA,GACzBrT,EAAQ2gB,gBAAkBA,GAC1B3gB,EAAQyT,QAAUA,GAClBzT,EAAQ8X,SAAWA,GACnB9X,EAAQ+hB,SAAW/N,GACnBhU,EAAQgU,cAAgBC,GACxBjU,EAAQ8gB,cAAgBA,GACxB9gB,EAAQuO,MAAQqS,GAChB5gB,EAAQkU,KAAOA,GACflU,EAAQ2Q,OAASA,GACjB3Q,EAAQoU,YAAcA,GACtBpU,EAAQuU,QAAUA,GAClBvU,EAAQ0U,WAAaA,GACrB1U,EAAQihB,OAASA,GACjBjhB,EAAQkhB,YAAcA,GACtBlhB,EAAQmhB,aAAeA,GACvBnhB,EAAQ6U,MAAQA,GAChB7U,EAAQohB,UAAYA,GACpBphB,EAAQ+Q,IAAMA,GACd/Q,EAAQ4V,OAASA,GACjB5V,EAAQ4X,aAAerV,GACvBvC,EAAQqhB,KAAOA,GACfrhB,EAAQuhB,UAAYA,GACpBvhB,EAAQwhB,WAAaA,GACrBxhB,EAAQ6V,OAASA,GACjB7V,EAAQkW,QAAUA,GAClBlW,EAAQkV,MAAQA,GAChBlV,EAAQgiB,WAAalL,GACrB9W,EAAQ0hB,YAAcA,GACtB1hB,EAAQsH,UAAYA,GACpBtH,EAAQmX,QAAUA,GAClBnX,EAAQsX,UAAYA,GACpBtX,EAAQwX,MAAQA,GAChBxX,EAAQ2hB,UAAYA,GACpB3hB,EAAQuX,OAASA,GACjBvX,EAAQiiB,IAAMhC,GACdjgB,EAAQkiB,SAAWhC,GACnBlgB,EAAQmiB,UAAYhC,GACpBngB,EAAQoiB,IAAMf,GACdrhB,EAAQqiB,SAAWd,GACnBvhB,EAAQsiB,UAAYd,GACpBxhB,EAAQuiB,KAAO1C,GACf7f,EAAQwiB,UAAY1C,GACpB9f,EAAQyiB,WAAa1C,GACrB/f,EAAQ0iB,QAAUtQ,GAClBpS,EAAQ2iB,cAAgBvL,GACxBpX,EAAQ4iB,aAAevQ,GACvBrS,EAAQ6iB,UAAYnZ,GACpB1J,EAAQ8iB,gBAAkBjS,GAC1B7Q,EAAQ+iB,eAAiB5Z,EACzBnJ,EAAQgjB,OAASrS,GACjB3Q,EAAQijB,MAAQtS,GAChB3Q,EAAQkjB,MAAQ9O,GAChBpU,EAAQmjB,OAASjQ,GACjBlT,EAAQojB,YAAchD,GACtBpgB,EAAQqjB,aAAehD,GACvBrgB,EAAQsjB,SAAW3hB,EAEnB0C,OAAOkf,eAAevjB,EAAS,cAAgBiB,OAAO","file":"build/dist/async.min.js"}
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/doDuring.js b/node_modules/webpack/node_modules/async/doDuring.js deleted file mode 100644 index 6812990b0..000000000 --- a/node_modules/webpack/node_modules/async/doDuring.js +++ /dev/null @@ -1,66 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = doDuring; - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _slice = require('./internal/slice'); - -var _slice2 = _interopRequireDefault(_slice); - -var _onlyOnce = require('./internal/onlyOnce'); - -var _onlyOnce2 = _interopRequireDefault(_onlyOnce); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The post-check version of [`during`]{@link module:ControlFlow.during}. To reflect the difference in - * the order of operations, the arguments `test` and `fn` are switched. - * - * Also a version of [`doWhilst`]{@link module:ControlFlow.doWhilst} with asynchronous `test` function. - * @name doDuring - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.during]{@link module:ControlFlow.during} - * @category Control Flow - * @param {AsyncFunction} fn - An async function which is called each time - * `test` passes. Invoked with (callback). - * @param {AsyncFunction} test - asynchronous truth test to perform before each - * execution of `fn`. Invoked with (...args, callback), where `...args` are the - * non-error args from the previous callback of `fn`. - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `fn` has stopped. `callback` - * will be passed an error if one occurred, otherwise `null`. - */ -function doDuring(fn, test, callback) { - callback = (0, _onlyOnce2.default)(callback || _noop2.default); - var _fn = (0, _wrapAsync2.default)(fn); - var _test = (0, _wrapAsync2.default)(test); - - function next(err /*, ...args*/) { - if (err) return callback(err); - var args = (0, _slice2.default)(arguments, 1); - args.push(check); - _test.apply(this, args); - }; - - function check(err, truth) { - if (err) return callback(err); - if (!truth) return callback(null); - _fn(next); - } - - check(null, true); -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/doUntil.js b/node_modules/webpack/node_modules/async/doUntil.js deleted file mode 100644 index 5a6a30f83..000000000 --- a/node_modules/webpack/node_modules/async/doUntil.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = doUntil; - -var _doWhilst = require('./doWhilst'); - -var _doWhilst2 = _interopRequireDefault(_doWhilst); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the - * argument ordering differs from `until`. - * - * @name doUntil - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.doWhilst]{@link module:ControlFlow.doWhilst} - * @category Control Flow - * @param {AsyncFunction} iteratee - An async function which is called each time - * `test` fails. Invoked with (callback). - * @param {Function} test - synchronous truth test to perform after each - * execution of `iteratee`. Invoked with any non-error callback results of - * `iteratee`. - * @param {Function} [callback] - A callback which is called after the test - * function has passed and repeated execution of `iteratee` has stopped. `callback` - * will be passed an error and any arguments passed to the final `iteratee`'s - * callback. Invoked with (err, [results]); - */ -function doUntil(iteratee, test, callback) { - (0, _doWhilst2.default)(iteratee, function () { - return !test.apply(this, arguments); - }, callback); -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/doWhilst.js b/node_modules/webpack/node_modules/async/doWhilst.js deleted file mode 100644 index d93511314..000000000 --- a/node_modules/webpack/node_modules/async/doWhilst.js +++ /dev/null @@ -1,59 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = doWhilst; - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _slice = require('./internal/slice'); - -var _slice2 = _interopRequireDefault(_slice); - -var _onlyOnce = require('./internal/onlyOnce'); - -var _onlyOnce2 = _interopRequireDefault(_onlyOnce); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in - * the order of operations, the arguments `test` and `iteratee` are switched. - * - * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. - * - * @name doWhilst - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.whilst]{@link module:ControlFlow.whilst} - * @category Control Flow - * @param {AsyncFunction} iteratee - A function which is called each time `test` - * passes. Invoked with (callback). - * @param {Function} test - synchronous truth test to perform after each - * execution of `iteratee`. Invoked with any non-error callback results of - * `iteratee`. - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `iteratee` has stopped. - * `callback` will be passed an error and any arguments passed to the final - * `iteratee`'s callback. Invoked with (err, [results]); - */ -function doWhilst(iteratee, test, callback) { - callback = (0, _onlyOnce2.default)(callback || _noop2.default); - var _iteratee = (0, _wrapAsync2.default)(iteratee); - var next = function (err /*, ...args*/) { - if (err) return callback(err); - var args = (0, _slice2.default)(arguments, 1); - if (test.apply(this, args)) return _iteratee(next); - callback.apply(null, [null].concat(args)); - }; - _iteratee(next); -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/during.js b/node_modules/webpack/node_modules/async/during.js deleted file mode 100644 index fd7343783..000000000 --- a/node_modules/webpack/node_modules/async/during.js +++ /dev/null @@ -1,76 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = during; - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _onlyOnce = require('./internal/onlyOnce'); - -var _onlyOnce2 = _interopRequireDefault(_onlyOnce); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Like [`whilst`]{@link module:ControlFlow.whilst}, except the `test` is an asynchronous function that - * is passed a callback in the form of `function (err, truth)`. If error is - * passed to `test` or `fn`, the main callback is immediately called with the - * value of the error. - * - * @name during - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.whilst]{@link module:ControlFlow.whilst} - * @category Control Flow - * @param {AsyncFunction} test - asynchronous truth test to perform before each - * execution of `fn`. Invoked with (callback). - * @param {AsyncFunction} fn - An async function which is called each time - * `test` passes. Invoked with (callback). - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `fn` has stopped. `callback` - * will be passed an error, if one occurred, otherwise `null`. - * @example - * - * var count = 0; - * - * async.during( - * function (callback) { - * return callback(null, count < 5); - * }, - * function (callback) { - * count++; - * setTimeout(callback, 1000); - * }, - * function (err) { - * // 5 seconds have passed - * } - * ); - */ -function during(test, fn, callback) { - callback = (0, _onlyOnce2.default)(callback || _noop2.default); - var _fn = (0, _wrapAsync2.default)(fn); - var _test = (0, _wrapAsync2.default)(test); - - function next(err) { - if (err) return callback(err); - _test(check); - } - - function check(err, truth) { - if (err) return callback(err); - if (!truth) return callback(null); - _fn(next); - } - - _test(check); -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/each.js b/node_modules/webpack/node_modules/async/each.js deleted file mode 100644 index 4b20af33d..000000000 --- a/node_modules/webpack/node_modules/async/each.js +++ /dev/null @@ -1,82 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = eachLimit; - -var _eachOf = require('./eachOf'); - -var _eachOf2 = _interopRequireDefault(_eachOf); - -var _withoutIndex = require('./internal/withoutIndex'); - -var _withoutIndex2 = _interopRequireDefault(_withoutIndex); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Applies the function `iteratee` to each item in `coll`, in parallel. - * The `iteratee` is called with an item from the list, and a callback for when - * it has finished. If the `iteratee` passes an error to its `callback`, the - * main `callback` (for the `each` function) is immediately called with the - * error. - * - * Note, that since this function applies `iteratee` to each item in parallel, - * there is no guarantee that the iteratee functions will complete in order. - * - * @name each - * @static - * @memberOf module:Collections - * @method - * @alias forEach - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to - * each item in `coll`. Invoked with (item, callback). - * The array index is not passed to the iteratee. - * If you need the index, use `eachOf`. - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - * @example - * - * // assuming openFiles is an array of file names and saveFile is a function - * // to save the modified contents of that file: - * - * async.each(openFiles, saveFile, function(err){ - * // if any of the saves produced an error, err would equal that error - * }); - * - * // assuming openFiles is an array of file names - * async.each(openFiles, function(file, callback) { - * - * // Perform operation on file here. - * console.log('Processing file ' + file); - * - * if( file.length > 32 ) { - * console.log('This file name is too long'); - * callback('File name too long'); - * } else { - * // Do work to process file here - * console.log('File processed'); - * callback(); - * } - * }, function(err) { - * // if any of the file processing produced an error, err would equal that error - * if( err ) { - * // One of the iterations produced an error. - * // All processing will now stop. - * console.log('A file failed to process'); - * } else { - * console.log('All files have been processed successfully'); - * } - * }); - */ -function eachLimit(coll, iteratee, callback) { - (0, _eachOf2.default)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/eachLimit.js b/node_modules/webpack/node_modules/async/eachLimit.js deleted file mode 100644 index fff721bce..000000000 --- a/node_modules/webpack/node_modules/async/eachLimit.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = eachLimit; - -var _eachOfLimit = require('./internal/eachOfLimit'); - -var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); - -var _withoutIndex = require('./internal/withoutIndex'); - -var _withoutIndex2 = _interopRequireDefault(_withoutIndex); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. - * - * @name eachLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.each]{@link module:Collections.each} - * @alias forEachLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The array index is not passed to the iteratee. - * If you need the index, use `eachOfLimit`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - */ -function eachLimit(coll, limit, iteratee, callback) { - (0, _eachOfLimit2.default)(limit)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/eachOf.js b/node_modules/webpack/node_modules/async/eachOf.js deleted file mode 100644 index 055b9bde1..000000000 --- a/node_modules/webpack/node_modules/async/eachOf.js +++ /dev/null @@ -1,111 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -exports.default = function (coll, iteratee, callback) { - var eachOfImplementation = (0, _isArrayLike2.default)(coll) ? eachOfArrayLike : eachOfGeneric; - eachOfImplementation(coll, (0, _wrapAsync2.default)(iteratee), callback); -}; - -var _isArrayLike = require('lodash/isArrayLike'); - -var _isArrayLike2 = _interopRequireDefault(_isArrayLike); - -var _breakLoop = require('./internal/breakLoop'); - -var _breakLoop2 = _interopRequireDefault(_breakLoop); - -var _eachOfLimit = require('./eachOfLimit'); - -var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _once = require('./internal/once'); - -var _once2 = _interopRequireDefault(_once); - -var _onlyOnce = require('./internal/onlyOnce'); - -var _onlyOnce2 = _interopRequireDefault(_onlyOnce); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -// eachOf implementation optimized for array-likes -function eachOfArrayLike(coll, iteratee, callback) { - callback = (0, _once2.default)(callback || _noop2.default); - var index = 0, - completed = 0, - length = coll.length; - if (length === 0) { - callback(null); - } - - function iteratorCallback(err, value) { - if (err) { - callback(err); - } else if (++completed === length || value === _breakLoop2.default) { - callback(null); - } - } - - for (; index < length; index++) { - iteratee(coll[index], index, (0, _onlyOnce2.default)(iteratorCallback)); - } -} - -// a generic version of eachOf which can handle array, object, and iterator cases. -var eachOfGeneric = (0, _doLimit2.default)(_eachOfLimit2.default, Infinity); - -/** - * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument - * to the iteratee. - * - * @name eachOf - * @static - * @memberOf module:Collections - * @method - * @alias forEachOf - * @category Collection - * @see [async.each]{@link module:Collections.each} - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each - * item in `coll`. - * The `key` is the item's key, or index in the case of an array. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - * @example - * - * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; - * var configs = {}; - * - * async.forEachOf(obj, function (value, key, callback) { - * fs.readFile(__dirname + value, "utf8", function (err, data) { - * if (err) return callback(err); - * try { - * configs[key] = JSON.parse(data); - * } catch (e) { - * return callback(e); - * } - * callback(); - * }); - * }, function (err) { - * if (err) console.error(err.message); - * // configs is now a map of JSON data - * doSomethingWith(configs); - * }); - */ -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/eachOfLimit.js b/node_modules/webpack/node_modules/async/eachOfLimit.js deleted file mode 100644 index 30a13299e..000000000 --- a/node_modules/webpack/node_modules/async/eachOfLimit.js +++ /dev/null @@ -1,41 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = eachOfLimit; - -var _eachOfLimit2 = require('./internal/eachOfLimit'); - -var _eachOfLimit3 = _interopRequireDefault(_eachOfLimit2); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a - * time. - * - * @name eachOfLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.eachOf]{@link module:Collections.eachOf} - * @alias forEachOfLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each - * item in `coll`. The `key` is the item's key, or index in the case of an - * array. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - */ -function eachOfLimit(coll, limit, iteratee, callback) { - (0, _eachOfLimit3.default)(limit)(coll, (0, _wrapAsync2.default)(iteratee), callback); -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/eachOfSeries.js b/node_modules/webpack/node_modules/async/eachOfSeries.js deleted file mode 100644 index 9dfd71134..000000000 --- a/node_modules/webpack/node_modules/async/eachOfSeries.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _eachOfLimit = require('./eachOfLimit'); - -var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. - * - * @name eachOfSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.eachOf]{@link module:Collections.eachOf} - * @alias forEachOfSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Invoked with (err). - */ -exports.default = (0, _doLimit2.default)(_eachOfLimit2.default, 1); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/eachSeries.js b/node_modules/webpack/node_modules/async/eachSeries.js deleted file mode 100644 index 55c78405e..000000000 --- a/node_modules/webpack/node_modules/async/eachSeries.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _eachLimit = require('./eachLimit'); - -var _eachLimit2 = _interopRequireDefault(_eachLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. - * - * @name eachSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.each]{@link module:Collections.each} - * @alias forEachSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each - * item in `coll`. - * The array index is not passed to the iteratee. - * If you need the index, use `eachOfSeries`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - */ -exports.default = (0, _doLimit2.default)(_eachLimit2.default, 1); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/ensureAsync.js b/node_modules/webpack/node_modules/async/ensureAsync.js deleted file mode 100644 index 1f57aecde..000000000 --- a/node_modules/webpack/node_modules/async/ensureAsync.js +++ /dev/null @@ -1,73 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = ensureAsync; - -var _setImmediate = require('./internal/setImmediate'); - -var _setImmediate2 = _interopRequireDefault(_setImmediate); - -var _initialParams = require('./internal/initialParams'); - -var _initialParams2 = _interopRequireDefault(_initialParams); - -var _wrapAsync = require('./internal/wrapAsync'); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Wrap an async function and ensure it calls its callback on a later tick of - * the event loop. If the function already calls its callback on a next tick, - * no extra deferral is added. This is useful for preventing stack overflows - * (`RangeError: Maximum call stack size exceeded`) and generally keeping - * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) - * contained. ES2017 `async` functions are returned as-is -- they are immune - * to Zalgo's corrupting influences, as they always resolve on a later tick. - * - * @name ensureAsync - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} fn - an async function, one that expects a node-style - * callback as its last argument. - * @returns {AsyncFunction} Returns a wrapped function with the exact same call - * signature as the function passed in. - * @example - * - * function sometimesAsync(arg, callback) { - * if (cache[arg]) { - * return callback(null, cache[arg]); // this would be synchronous!! - * } else { - * doSomeIO(arg, callback); // this IO would be asynchronous - * } - * } - * - * // this has a risk of stack overflows if many results are cached in a row - * async.mapSeries(args, sometimesAsync, done); - * - * // this will defer sometimesAsync's callback if necessary, - * // preventing stack overflows - * async.mapSeries(args, async.ensureAsync(sometimesAsync), done); - */ -function ensureAsync(fn) { - if ((0, _wrapAsync.isAsync)(fn)) return fn; - return (0, _initialParams2.default)(function (args, callback) { - var sync = true; - args.push(function () { - var innerArgs = arguments; - if (sync) { - (0, _setImmediate2.default)(function () { - callback.apply(null, innerArgs); - }); - } else { - callback.apply(null, innerArgs); - } - }); - fn.apply(this, args); - sync = false; - }); -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/every.js b/node_modules/webpack/node_modules/async/every.js deleted file mode 100644 index d0565b045..000000000 --- a/node_modules/webpack/node_modules/async/every.js +++ /dev/null @@ -1,50 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createTester = require('./internal/createTester'); - -var _createTester2 = _interopRequireDefault(_createTester); - -var _doParallel = require('./internal/doParallel'); - -var _doParallel2 = _interopRequireDefault(_doParallel); - -var _notId = require('./internal/notId'); - -var _notId2 = _interopRequireDefault(_notId); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Returns `true` if every element in `coll` satisfies an async test. If any - * iteratee call returns `false`, the main `callback` is immediately called. - * - * @name every - * @static - * @memberOf module:Collections - * @method - * @alias all - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in parallel. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - * @example - * - * async.every(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // if result is true then every file exists - * }); - */ -exports.default = (0, _doParallel2.default)((0, _createTester2.default)(_notId2.default, _notId2.default)); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/everyLimit.js b/node_modules/webpack/node_modules/async/everyLimit.js deleted file mode 100644 index a1a759a2b..000000000 --- a/node_modules/webpack/node_modules/async/everyLimit.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createTester = require('./internal/createTester'); - -var _createTester2 = _interopRequireDefault(_createTester); - -var _doParallelLimit = require('./internal/doParallelLimit'); - -var _doParallelLimit2 = _interopRequireDefault(_doParallelLimit); - -var _notId = require('./internal/notId'); - -var _notId2 = _interopRequireDefault(_notId); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. - * - * @name everyLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.every]{@link module:Collections.every} - * @alias allLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in parallel. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - */ -exports.default = (0, _doParallelLimit2.default)((0, _createTester2.default)(_notId2.default, _notId2.default)); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/everySeries.js b/node_modules/webpack/node_modules/async/everySeries.js deleted file mode 100644 index 23bfebb59..000000000 --- a/node_modules/webpack/node_modules/async/everySeries.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _everyLimit = require('./everyLimit'); - -var _everyLimit2 = _interopRequireDefault(_everyLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. - * - * @name everySeries - * @static - * @memberOf module:Collections - * @method - * @see [async.every]{@link module:Collections.every} - * @alias allSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in series. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - */ -exports.default = (0, _doLimit2.default)(_everyLimit2.default, 1); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/filter.js b/node_modules/webpack/node_modules/async/filter.js deleted file mode 100644 index 54772d562..000000000 --- a/node_modules/webpack/node_modules/async/filter.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _filter = require('./internal/filter'); - -var _filter2 = _interopRequireDefault(_filter); - -var _doParallel = require('./internal/doParallel'); - -var _doParallel2 = _interopRequireDefault(_doParallel); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Returns a new array of all the values in `coll` which pass an async truth - * test. This operation is performed in parallel, but the results array will be - * in the same order as the original. - * - * @name filter - * @static - * @memberOf module:Collections - * @method - * @alias select - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - A truth test to apply to each item in `coll`. - * The `iteratee` is passed a `callback(err, truthValue)`, which must be called - * with a boolean argument once it has completed. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - * @example - * - * async.filter(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, results) { - * // results now equals an array of the existing files - * }); - */ -exports.default = (0, _doParallel2.default)(_filter2.default); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/filterLimit.js b/node_modules/webpack/node_modules/async/filterLimit.js deleted file mode 100644 index 06216f785..000000000 --- a/node_modules/webpack/node_modules/async/filterLimit.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _filter = require('./internal/filter'); - -var _filter2 = _interopRequireDefault(_filter); - -var _doParallelLimit = require('./internal/doParallelLimit'); - -var _doParallelLimit2 = _interopRequireDefault(_doParallelLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a - * time. - * - * @name filterLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.filter]{@link module:Collections.filter} - * @alias selectLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {Function} iteratee - A truth test to apply to each item in `coll`. - * The `iteratee` is passed a `callback(err, truthValue)`, which must be called - * with a boolean argument once it has completed. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - */ -exports.default = (0, _doParallelLimit2.default)(_filter2.default); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/filterSeries.js b/node_modules/webpack/node_modules/async/filterSeries.js deleted file mode 100644 index e48d966cb..000000000 --- a/node_modules/webpack/node_modules/async/filterSeries.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _filterLimit = require('./filterLimit'); - -var _filterLimit2 = _interopRequireDefault(_filterLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. - * - * @name filterSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.filter]{@link module:Collections.filter} - * @alias selectSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - A truth test to apply to each item in `coll`. - * The `iteratee` is passed a `callback(err, truthValue)`, which must be called - * with a boolean argument once it has completed. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results) - */ -exports.default = (0, _doLimit2.default)(_filterLimit2.default, 1); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/find.js b/node_modules/webpack/node_modules/async/find.js deleted file mode 100644 index db4678358..000000000 --- a/node_modules/webpack/node_modules/async/find.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _identity = require('lodash/identity'); - -var _identity2 = _interopRequireDefault(_identity); - -var _createTester = require('./internal/createTester'); - -var _createTester2 = _interopRequireDefault(_createTester); - -var _doParallel = require('./internal/doParallel'); - -var _doParallel2 = _interopRequireDefault(_doParallel); - -var _findGetResult = require('./internal/findGetResult'); - -var _findGetResult2 = _interopRequireDefault(_findGetResult); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Returns the first value in `coll` that passes an async truth test. The - * `iteratee` is applied in parallel, meaning the first iteratee to return - * `true` will fire the detect `callback` with that result. That means the - * result might not be the first item in the original `coll` (in terms of order) - * that passes the test. - - * If order within the original `coll` is important, then look at - * [`detectSeries`]{@link module:Collections.detectSeries}. - * - * @name detect - * @static - * @memberOf module:Collections - * @method - * @alias find - * @category Collections - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. - * The iteratee must complete with a boolean value as its result. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the `iteratee` functions have finished. - * Result will be the first item in the array that passes the truth test - * (iteratee) or the value `undefined` if none passed. Invoked with - * (err, result). - * @example - * - * async.detect(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // result now equals the first file in the list that exists - * }); - */ -exports.default = (0, _doParallel2.default)((0, _createTester2.default)(_identity2.default, _findGetResult2.default)); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/findLimit.js b/node_modules/webpack/node_modules/async/findLimit.js deleted file mode 100644 index 6bf656022..000000000 --- a/node_modules/webpack/node_modules/async/findLimit.js +++ /dev/null @@ -1,48 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _identity = require('lodash/identity'); - -var _identity2 = _interopRequireDefault(_identity); - -var _createTester = require('./internal/createTester'); - -var _createTester2 = _interopRequireDefault(_createTester); - -var _doParallelLimit = require('./internal/doParallelLimit'); - -var _doParallelLimit2 = _interopRequireDefault(_doParallelLimit); - -var _findGetResult = require('./internal/findGetResult'); - -var _findGetResult2 = _interopRequireDefault(_findGetResult); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a - * time. - * - * @name detectLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.detect]{@link module:Collections.detect} - * @alias findLimit - * @category Collections - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. - * The iteratee must complete with a boolean value as its result. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the `iteratee` functions have finished. - * Result will be the first item in the array that passes the truth test - * (iteratee) or the value `undefined` if none passed. Invoked with - * (err, result). - */ -exports.default = (0, _doParallelLimit2.default)((0, _createTester2.default)(_identity2.default, _findGetResult2.default)); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/findSeries.js b/node_modules/webpack/node_modules/async/findSeries.js deleted file mode 100644 index 6fe16c956..000000000 --- a/node_modules/webpack/node_modules/async/findSeries.js +++ /dev/null @@ -1,38 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _detectLimit = require('./detectLimit'); - -var _detectLimit2 = _interopRequireDefault(_detectLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. - * - * @name detectSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.detect]{@link module:Collections.detect} - * @alias findSeries - * @category Collections - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. - * The iteratee must complete with a boolean value as its result. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the `iteratee` functions have finished. - * Result will be the first item in the array that passes the truth test - * (iteratee) or the value `undefined` if none passed. Invoked with - * (err, result). - */ -exports.default = (0, _doLimit2.default)(_detectLimit2.default, 1); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/foldl.js b/node_modules/webpack/node_modules/async/foldl.js deleted file mode 100644 index 3fb8019e4..000000000 --- a/node_modules/webpack/node_modules/async/foldl.js +++ /dev/null @@ -1,78 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = reduce; - -var _eachOfSeries = require('./eachOfSeries'); - -var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _once = require('./internal/once'); - -var _once2 = _interopRequireDefault(_once); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Reduces `coll` into a single value using an async `iteratee` to return each - * successive step. `memo` is the initial state of the reduction. This function - * only operates in series. - * - * For performance reasons, it may make sense to split a call to this function - * into a parallel map, and then use the normal `Array.prototype.reduce` on the - * results. This function is for situations where each step in the reduction - * needs to be async; if you can get the data before reducing it, then it's - * probably a good idea to do so. - * - * @name reduce - * @static - * @memberOf module:Collections - * @method - * @alias inject - * @alias foldl - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {*} memo - The initial state of the reduction. - * @param {AsyncFunction} iteratee - A function applied to each item in the - * array to produce the next step in the reduction. - * The `iteratee` should complete with the next state of the reduction. - * If the iteratee complete with an error, the reduction is stopped and the - * main `callback` is immediately called with the error. - * Invoked with (memo, item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result is the reduced value. Invoked with - * (err, result). - * @example - * - * async.reduce([1,2,3], 0, function(memo, item, callback) { - * // pointless async: - * process.nextTick(function() { - * callback(null, memo + item) - * }); - * }, function(err, result) { - * // result is now equal to the last value of memo, which is 6 - * }); - */ -function reduce(coll, memo, iteratee, callback) { - callback = (0, _once2.default)(callback || _noop2.default); - var _iteratee = (0, _wrapAsync2.default)(iteratee); - (0, _eachOfSeries2.default)(coll, function (x, i, callback) { - _iteratee(memo, x, function (err, v) { - memo = v; - callback(err); - }); - }, function (err) { - callback(err, memo); - }); -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/foldr.js b/node_modules/webpack/node_modules/async/foldr.js deleted file mode 100644 index 3d17d328a..000000000 --- a/node_modules/webpack/node_modules/async/foldr.js +++ /dev/null @@ -1,44 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = reduceRight; - -var _reduce = require('./reduce'); - -var _reduce2 = _interopRequireDefault(_reduce); - -var _slice = require('./internal/slice'); - -var _slice2 = _interopRequireDefault(_slice); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. - * - * @name reduceRight - * @static - * @memberOf module:Collections - * @method - * @see [async.reduce]{@link module:Collections.reduce} - * @alias foldr - * @category Collection - * @param {Array} array - A collection to iterate over. - * @param {*} memo - The initial state of the reduction. - * @param {AsyncFunction} iteratee - A function applied to each item in the - * array to produce the next step in the reduction. - * The `iteratee` should complete with the next state of the reduction. - * If the iteratee complete with an error, the reduction is stopped and the - * main `callback` is immediately called with the error. - * Invoked with (memo, item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result is the reduced value. Invoked with - * (err, result). - */ -function reduceRight(array, memo, iteratee, callback) { - var reversed = (0, _slice2.default)(array).reverse(); - (0, _reduce2.default)(reversed, memo, iteratee, callback); -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/forEach.js b/node_modules/webpack/node_modules/async/forEach.js deleted file mode 100644 index 4b20af33d..000000000 --- a/node_modules/webpack/node_modules/async/forEach.js +++ /dev/null @@ -1,82 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = eachLimit; - -var _eachOf = require('./eachOf'); - -var _eachOf2 = _interopRequireDefault(_eachOf); - -var _withoutIndex = require('./internal/withoutIndex'); - -var _withoutIndex2 = _interopRequireDefault(_withoutIndex); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Applies the function `iteratee` to each item in `coll`, in parallel. - * The `iteratee` is called with an item from the list, and a callback for when - * it has finished. If the `iteratee` passes an error to its `callback`, the - * main `callback` (for the `each` function) is immediately called with the - * error. - * - * Note, that since this function applies `iteratee` to each item in parallel, - * there is no guarantee that the iteratee functions will complete in order. - * - * @name each - * @static - * @memberOf module:Collections - * @method - * @alias forEach - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to - * each item in `coll`. Invoked with (item, callback). - * The array index is not passed to the iteratee. - * If you need the index, use `eachOf`. - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - * @example - * - * // assuming openFiles is an array of file names and saveFile is a function - * // to save the modified contents of that file: - * - * async.each(openFiles, saveFile, function(err){ - * // if any of the saves produced an error, err would equal that error - * }); - * - * // assuming openFiles is an array of file names - * async.each(openFiles, function(file, callback) { - * - * // Perform operation on file here. - * console.log('Processing file ' + file); - * - * if( file.length > 32 ) { - * console.log('This file name is too long'); - * callback('File name too long'); - * } else { - * // Do work to process file here - * console.log('File processed'); - * callback(); - * } - * }, function(err) { - * // if any of the file processing produced an error, err would equal that error - * if( err ) { - * // One of the iterations produced an error. - * // All processing will now stop. - * console.log('A file failed to process'); - * } else { - * console.log('All files have been processed successfully'); - * } - * }); - */ -function eachLimit(coll, iteratee, callback) { - (0, _eachOf2.default)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/forEachLimit.js b/node_modules/webpack/node_modules/async/forEachLimit.js deleted file mode 100644 index fff721bce..000000000 --- a/node_modules/webpack/node_modules/async/forEachLimit.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = eachLimit; - -var _eachOfLimit = require('./internal/eachOfLimit'); - -var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); - -var _withoutIndex = require('./internal/withoutIndex'); - -var _withoutIndex2 = _interopRequireDefault(_withoutIndex); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. - * - * @name eachLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.each]{@link module:Collections.each} - * @alias forEachLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The array index is not passed to the iteratee. - * If you need the index, use `eachOfLimit`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - */ -function eachLimit(coll, limit, iteratee, callback) { - (0, _eachOfLimit2.default)(limit)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/forEachOf.js b/node_modules/webpack/node_modules/async/forEachOf.js deleted file mode 100644 index 055b9bde1..000000000 --- a/node_modules/webpack/node_modules/async/forEachOf.js +++ /dev/null @@ -1,111 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -exports.default = function (coll, iteratee, callback) { - var eachOfImplementation = (0, _isArrayLike2.default)(coll) ? eachOfArrayLike : eachOfGeneric; - eachOfImplementation(coll, (0, _wrapAsync2.default)(iteratee), callback); -}; - -var _isArrayLike = require('lodash/isArrayLike'); - -var _isArrayLike2 = _interopRequireDefault(_isArrayLike); - -var _breakLoop = require('./internal/breakLoop'); - -var _breakLoop2 = _interopRequireDefault(_breakLoop); - -var _eachOfLimit = require('./eachOfLimit'); - -var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _once = require('./internal/once'); - -var _once2 = _interopRequireDefault(_once); - -var _onlyOnce = require('./internal/onlyOnce'); - -var _onlyOnce2 = _interopRequireDefault(_onlyOnce); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -// eachOf implementation optimized for array-likes -function eachOfArrayLike(coll, iteratee, callback) { - callback = (0, _once2.default)(callback || _noop2.default); - var index = 0, - completed = 0, - length = coll.length; - if (length === 0) { - callback(null); - } - - function iteratorCallback(err, value) { - if (err) { - callback(err); - } else if (++completed === length || value === _breakLoop2.default) { - callback(null); - } - } - - for (; index < length; index++) { - iteratee(coll[index], index, (0, _onlyOnce2.default)(iteratorCallback)); - } -} - -// a generic version of eachOf which can handle array, object, and iterator cases. -var eachOfGeneric = (0, _doLimit2.default)(_eachOfLimit2.default, Infinity); - -/** - * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument - * to the iteratee. - * - * @name eachOf - * @static - * @memberOf module:Collections - * @method - * @alias forEachOf - * @category Collection - * @see [async.each]{@link module:Collections.each} - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each - * item in `coll`. - * The `key` is the item's key, or index in the case of an array. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - * @example - * - * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; - * var configs = {}; - * - * async.forEachOf(obj, function (value, key, callback) { - * fs.readFile(__dirname + value, "utf8", function (err, data) { - * if (err) return callback(err); - * try { - * configs[key] = JSON.parse(data); - * } catch (e) { - * return callback(e); - * } - * callback(); - * }); - * }, function (err) { - * if (err) console.error(err.message); - * // configs is now a map of JSON data - * doSomethingWith(configs); - * }); - */ -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/forEachOfLimit.js b/node_modules/webpack/node_modules/async/forEachOfLimit.js deleted file mode 100644 index 30a13299e..000000000 --- a/node_modules/webpack/node_modules/async/forEachOfLimit.js +++ /dev/null @@ -1,41 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = eachOfLimit; - -var _eachOfLimit2 = require('./internal/eachOfLimit'); - -var _eachOfLimit3 = _interopRequireDefault(_eachOfLimit2); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a - * time. - * - * @name eachOfLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.eachOf]{@link module:Collections.eachOf} - * @alias forEachOfLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each - * item in `coll`. The `key` is the item's key, or index in the case of an - * array. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - */ -function eachOfLimit(coll, limit, iteratee, callback) { - (0, _eachOfLimit3.default)(limit)(coll, (0, _wrapAsync2.default)(iteratee), callback); -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/forEachOfSeries.js b/node_modules/webpack/node_modules/async/forEachOfSeries.js deleted file mode 100644 index 9dfd71134..000000000 --- a/node_modules/webpack/node_modules/async/forEachOfSeries.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _eachOfLimit = require('./eachOfLimit'); - -var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. - * - * @name eachOfSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.eachOf]{@link module:Collections.eachOf} - * @alias forEachOfSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Invoked with (err). - */ -exports.default = (0, _doLimit2.default)(_eachOfLimit2.default, 1); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/forEachSeries.js b/node_modules/webpack/node_modules/async/forEachSeries.js deleted file mode 100644 index 55c78405e..000000000 --- a/node_modules/webpack/node_modules/async/forEachSeries.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _eachLimit = require('./eachLimit'); - -var _eachLimit2 = _interopRequireDefault(_eachLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. - * - * @name eachSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.each]{@link module:Collections.each} - * @alias forEachSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each - * item in `coll`. - * The array index is not passed to the iteratee. - * If you need the index, use `eachOfSeries`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - */ -exports.default = (0, _doLimit2.default)(_eachLimit2.default, 1); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/forever.js b/node_modules/webpack/node_modules/async/forever.js deleted file mode 100644 index 6c7b8a4cd..000000000 --- a/node_modules/webpack/node_modules/async/forever.js +++ /dev/null @@ -1,65 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = forever; - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _onlyOnce = require('./internal/onlyOnce'); - -var _onlyOnce2 = _interopRequireDefault(_onlyOnce); - -var _ensureAsync = require('./ensureAsync'); - -var _ensureAsync2 = _interopRequireDefault(_ensureAsync); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Calls the asynchronous function `fn` with a callback parameter that allows it - * to call itself again, in series, indefinitely. - - * If an error is passed to the callback then `errback` is called with the - * error, and execution stops, otherwise it will never be called. - * - * @name forever - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {AsyncFunction} fn - an async function to call repeatedly. - * Invoked with (next). - * @param {Function} [errback] - when `fn` passes an error to it's callback, - * this function will be called, and execution stops. Invoked with (err). - * @example - * - * async.forever( - * function(next) { - * // next is suitable for passing to things that need a callback(err [, whatever]); - * // it will result in this function being called again. - * }, - * function(err) { - * // if next is called with a value in its first parameter, it will appear - * // in here as 'err', and execution will stop. - * } - * ); - */ -function forever(fn, errback) { - var done = (0, _onlyOnce2.default)(errback || _noop2.default); - var task = (0, _wrapAsync2.default)((0, _ensureAsync2.default)(fn)); - - function next(err) { - if (err) return done(err); - task(next); - } - next(); -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/groupBy.js b/node_modules/webpack/node_modules/async/groupBy.js deleted file mode 100644 index 755cba764..000000000 --- a/node_modules/webpack/node_modules/async/groupBy.js +++ /dev/null @@ -1,54 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -var _groupByLimit = require('./groupByLimit'); - -var _groupByLimit2 = _interopRequireDefault(_groupByLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Returns a new object, where each value corresponds to an array of items, from - * `coll`, that returned the corresponding key. That is, the keys of the object - * correspond to the values passed to the `iteratee` callback. - * - * Note: Since this function applies the `iteratee` to each item in parallel, - * there is no guarantee that the `iteratee` functions will complete in order. - * However, the values for each key in the `result` will be in the same order as - * the original `coll`. For Objects, the values will roughly be in the order of - * the original Objects' keys (but this can vary across JavaScript engines). - * - * @name groupBy - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a `key` to group the value under. - * Invoked with (value, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Result is an `Object` whoses - * properties are arrays of values which returned the corresponding key. - * @example - * - * async.groupBy(['userId1', 'userId2', 'userId3'], function(userId, callback) { - * db.findById(userId, function(err, user) { - * if (err) return callback(err); - * return callback(null, user.age); - * }); - * }, function(err, result) { - * // result is object containing the userIds grouped by age - * // e.g. { 30: ['userId1', 'userId3'], 42: ['userId2']}; - * }); - */ -exports.default = (0, _doLimit2.default)(_groupByLimit2.default, Infinity); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/groupByLimit.js b/node_modules/webpack/node_modules/async/groupByLimit.js deleted file mode 100644 index fec13f865..000000000 --- a/node_modules/webpack/node_modules/async/groupByLimit.js +++ /dev/null @@ -1,71 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -exports.default = function (coll, limit, iteratee, callback) { - callback = callback || _noop2.default; - var _iteratee = (0, _wrapAsync2.default)(iteratee); - (0, _mapLimit2.default)(coll, limit, function (val, callback) { - _iteratee(val, function (err, key) { - if (err) return callback(err); - return callback(null, { key: key, val: val }); - }); - }, function (err, mapResults) { - var result = {}; - // from MDN, handle object having an `hasOwnProperty` prop - var hasOwnProperty = Object.prototype.hasOwnProperty; - - for (var i = 0; i < mapResults.length; i++) { - if (mapResults[i]) { - var key = mapResults[i].key; - var val = mapResults[i].val; - - if (hasOwnProperty.call(result, key)) { - result[key].push(val); - } else { - result[key] = [val]; - } - } - } - - return callback(err, result); - }); -}; - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _mapLimit = require('./mapLimit'); - -var _mapLimit2 = _interopRequireDefault(_mapLimit); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -; -/** - * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time. - * - * @name groupByLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.groupBy]{@link module:Collections.groupBy} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a `key` to group the value under. - * Invoked with (value, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Result is an `Object` whoses - * properties are arrays of values which returned the corresponding key. - */ -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/groupBySeries.js b/node_modules/webpack/node_modules/async/groupBySeries.js deleted file mode 100644 index b94805e35..000000000 --- a/node_modules/webpack/node_modules/async/groupBySeries.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -var _groupByLimit = require('./groupByLimit'); - -var _groupByLimit2 = _interopRequireDefault(_groupByLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time. - * - * @name groupBySeries - * @static - * @memberOf module:Collections - * @method - * @see [async.groupBy]{@link module:Collections.groupBy} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a `key` to group the value under. - * Invoked with (value, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Result is an `Object` whoses - * properties are arrays of values which returned the corresponding key. - */ -exports.default = (0, _doLimit2.default)(_groupByLimit2.default, 1); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/index.js b/node_modules/webpack/node_modules/async/index.js deleted file mode 100644 index c39d8d8ec..000000000 --- a/node_modules/webpack/node_modules/async/index.js +++ /dev/null @@ -1,582 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.wrapSync = exports.selectSeries = exports.selectLimit = exports.select = exports.foldr = exports.foldl = exports.inject = exports.forEachOfLimit = exports.forEachOfSeries = exports.forEachOf = exports.forEachLimit = exports.forEachSeries = exports.forEach = exports.findSeries = exports.findLimit = exports.find = exports.anySeries = exports.anyLimit = exports.any = exports.allSeries = exports.allLimit = exports.all = exports.whilst = exports.waterfall = exports.until = exports.unmemoize = exports.tryEach = exports.transform = exports.timesSeries = exports.timesLimit = exports.times = exports.timeout = exports.sortBy = exports.someSeries = exports.someLimit = exports.some = exports.setImmediate = exports.series = exports.seq = exports.retryable = exports.retry = exports.rejectSeries = exports.rejectLimit = exports.reject = exports.reflectAll = exports.reflect = exports.reduceRight = exports.reduce = exports.race = exports.queue = exports.priorityQueue = exports.parallelLimit = exports.parallel = exports.nextTick = exports.memoize = exports.mapValuesSeries = exports.mapValuesLimit = exports.mapValues = exports.mapSeries = exports.mapLimit = exports.map = exports.log = exports.groupBySeries = exports.groupByLimit = exports.groupBy = exports.forever = exports.filterSeries = exports.filterLimit = exports.filter = exports.everySeries = exports.everyLimit = exports.every = exports.ensureAsync = exports.eachSeries = exports.eachOfSeries = exports.eachOfLimit = exports.eachOf = exports.eachLimit = exports.each = exports.during = exports.doWhilst = exports.doUntil = exports.doDuring = exports.dir = exports.detectSeries = exports.detectLimit = exports.detect = exports.constant = exports.concatSeries = exports.concatLimit = exports.concat = exports.compose = exports.cargo = exports.autoInject = exports.auto = exports.asyncify = exports.applyEachSeries = exports.applyEach = exports.apply = undefined; - -var _apply = require('./apply'); - -var _apply2 = _interopRequireDefault(_apply); - -var _applyEach = require('./applyEach'); - -var _applyEach2 = _interopRequireDefault(_applyEach); - -var _applyEachSeries = require('./applyEachSeries'); - -var _applyEachSeries2 = _interopRequireDefault(_applyEachSeries); - -var _asyncify = require('./asyncify'); - -var _asyncify2 = _interopRequireDefault(_asyncify); - -var _auto = require('./auto'); - -var _auto2 = _interopRequireDefault(_auto); - -var _autoInject = require('./autoInject'); - -var _autoInject2 = _interopRequireDefault(_autoInject); - -var _cargo = require('./cargo'); - -var _cargo2 = _interopRequireDefault(_cargo); - -var _compose = require('./compose'); - -var _compose2 = _interopRequireDefault(_compose); - -var _concat = require('./concat'); - -var _concat2 = _interopRequireDefault(_concat); - -var _concatLimit = require('./concatLimit'); - -var _concatLimit2 = _interopRequireDefault(_concatLimit); - -var _concatSeries = require('./concatSeries'); - -var _concatSeries2 = _interopRequireDefault(_concatSeries); - -var _constant = require('./constant'); - -var _constant2 = _interopRequireDefault(_constant); - -var _detect = require('./detect'); - -var _detect2 = _interopRequireDefault(_detect); - -var _detectLimit = require('./detectLimit'); - -var _detectLimit2 = _interopRequireDefault(_detectLimit); - -var _detectSeries = require('./detectSeries'); - -var _detectSeries2 = _interopRequireDefault(_detectSeries); - -var _dir = require('./dir'); - -var _dir2 = _interopRequireDefault(_dir); - -var _doDuring = require('./doDuring'); - -var _doDuring2 = _interopRequireDefault(_doDuring); - -var _doUntil = require('./doUntil'); - -var _doUntil2 = _interopRequireDefault(_doUntil); - -var _doWhilst = require('./doWhilst'); - -var _doWhilst2 = _interopRequireDefault(_doWhilst); - -var _during = require('./during'); - -var _during2 = _interopRequireDefault(_during); - -var _each = require('./each'); - -var _each2 = _interopRequireDefault(_each); - -var _eachLimit = require('./eachLimit'); - -var _eachLimit2 = _interopRequireDefault(_eachLimit); - -var _eachOf = require('./eachOf'); - -var _eachOf2 = _interopRequireDefault(_eachOf); - -var _eachOfLimit = require('./eachOfLimit'); - -var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); - -var _eachOfSeries = require('./eachOfSeries'); - -var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); - -var _eachSeries = require('./eachSeries'); - -var _eachSeries2 = _interopRequireDefault(_eachSeries); - -var _ensureAsync = require('./ensureAsync'); - -var _ensureAsync2 = _interopRequireDefault(_ensureAsync); - -var _every = require('./every'); - -var _every2 = _interopRequireDefault(_every); - -var _everyLimit = require('./everyLimit'); - -var _everyLimit2 = _interopRequireDefault(_everyLimit); - -var _everySeries = require('./everySeries'); - -var _everySeries2 = _interopRequireDefault(_everySeries); - -var _filter = require('./filter'); - -var _filter2 = _interopRequireDefault(_filter); - -var _filterLimit = require('./filterLimit'); - -var _filterLimit2 = _interopRequireDefault(_filterLimit); - -var _filterSeries = require('./filterSeries'); - -var _filterSeries2 = _interopRequireDefault(_filterSeries); - -var _forever = require('./forever'); - -var _forever2 = _interopRequireDefault(_forever); - -var _groupBy = require('./groupBy'); - -var _groupBy2 = _interopRequireDefault(_groupBy); - -var _groupByLimit = require('./groupByLimit'); - -var _groupByLimit2 = _interopRequireDefault(_groupByLimit); - -var _groupBySeries = require('./groupBySeries'); - -var _groupBySeries2 = _interopRequireDefault(_groupBySeries); - -var _log = require('./log'); - -var _log2 = _interopRequireDefault(_log); - -var _map = require('./map'); - -var _map2 = _interopRequireDefault(_map); - -var _mapLimit = require('./mapLimit'); - -var _mapLimit2 = _interopRequireDefault(_mapLimit); - -var _mapSeries = require('./mapSeries'); - -var _mapSeries2 = _interopRequireDefault(_mapSeries); - -var _mapValues = require('./mapValues'); - -var _mapValues2 = _interopRequireDefault(_mapValues); - -var _mapValuesLimit = require('./mapValuesLimit'); - -var _mapValuesLimit2 = _interopRequireDefault(_mapValuesLimit); - -var _mapValuesSeries = require('./mapValuesSeries'); - -var _mapValuesSeries2 = _interopRequireDefault(_mapValuesSeries); - -var _memoize = require('./memoize'); - -var _memoize2 = _interopRequireDefault(_memoize); - -var _nextTick = require('./nextTick'); - -var _nextTick2 = _interopRequireDefault(_nextTick); - -var _parallel = require('./parallel'); - -var _parallel2 = _interopRequireDefault(_parallel); - -var _parallelLimit = require('./parallelLimit'); - -var _parallelLimit2 = _interopRequireDefault(_parallelLimit); - -var _priorityQueue = require('./priorityQueue'); - -var _priorityQueue2 = _interopRequireDefault(_priorityQueue); - -var _queue = require('./queue'); - -var _queue2 = _interopRequireDefault(_queue); - -var _race = require('./race'); - -var _race2 = _interopRequireDefault(_race); - -var _reduce = require('./reduce'); - -var _reduce2 = _interopRequireDefault(_reduce); - -var _reduceRight = require('./reduceRight'); - -var _reduceRight2 = _interopRequireDefault(_reduceRight); - -var _reflect = require('./reflect'); - -var _reflect2 = _interopRequireDefault(_reflect); - -var _reflectAll = require('./reflectAll'); - -var _reflectAll2 = _interopRequireDefault(_reflectAll); - -var _reject = require('./reject'); - -var _reject2 = _interopRequireDefault(_reject); - -var _rejectLimit = require('./rejectLimit'); - -var _rejectLimit2 = _interopRequireDefault(_rejectLimit); - -var _rejectSeries = require('./rejectSeries'); - -var _rejectSeries2 = _interopRequireDefault(_rejectSeries); - -var _retry = require('./retry'); - -var _retry2 = _interopRequireDefault(_retry); - -var _retryable = require('./retryable'); - -var _retryable2 = _interopRequireDefault(_retryable); - -var _seq = require('./seq'); - -var _seq2 = _interopRequireDefault(_seq); - -var _series = require('./series'); - -var _series2 = _interopRequireDefault(_series); - -var _setImmediate = require('./setImmediate'); - -var _setImmediate2 = _interopRequireDefault(_setImmediate); - -var _some = require('./some'); - -var _some2 = _interopRequireDefault(_some); - -var _someLimit = require('./someLimit'); - -var _someLimit2 = _interopRequireDefault(_someLimit); - -var _someSeries = require('./someSeries'); - -var _someSeries2 = _interopRequireDefault(_someSeries); - -var _sortBy = require('./sortBy'); - -var _sortBy2 = _interopRequireDefault(_sortBy); - -var _timeout = require('./timeout'); - -var _timeout2 = _interopRequireDefault(_timeout); - -var _times = require('./times'); - -var _times2 = _interopRequireDefault(_times); - -var _timesLimit = require('./timesLimit'); - -var _timesLimit2 = _interopRequireDefault(_timesLimit); - -var _timesSeries = require('./timesSeries'); - -var _timesSeries2 = _interopRequireDefault(_timesSeries); - -var _transform = require('./transform'); - -var _transform2 = _interopRequireDefault(_transform); - -var _tryEach = require('./tryEach'); - -var _tryEach2 = _interopRequireDefault(_tryEach); - -var _unmemoize = require('./unmemoize'); - -var _unmemoize2 = _interopRequireDefault(_unmemoize); - -var _until = require('./until'); - -var _until2 = _interopRequireDefault(_until); - -var _waterfall = require('./waterfall'); - -var _waterfall2 = _interopRequireDefault(_waterfall); - -var _whilst = require('./whilst'); - -var _whilst2 = _interopRequireDefault(_whilst); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -exports.default = { - apply: _apply2.default, - applyEach: _applyEach2.default, - applyEachSeries: _applyEachSeries2.default, - asyncify: _asyncify2.default, - auto: _auto2.default, - autoInject: _autoInject2.default, - cargo: _cargo2.default, - compose: _compose2.default, - concat: _concat2.default, - concatLimit: _concatLimit2.default, - concatSeries: _concatSeries2.default, - constant: _constant2.default, - detect: _detect2.default, - detectLimit: _detectLimit2.default, - detectSeries: _detectSeries2.default, - dir: _dir2.default, - doDuring: _doDuring2.default, - doUntil: _doUntil2.default, - doWhilst: _doWhilst2.default, - during: _during2.default, - each: _each2.default, - eachLimit: _eachLimit2.default, - eachOf: _eachOf2.default, - eachOfLimit: _eachOfLimit2.default, - eachOfSeries: _eachOfSeries2.default, - eachSeries: _eachSeries2.default, - ensureAsync: _ensureAsync2.default, - every: _every2.default, - everyLimit: _everyLimit2.default, - everySeries: _everySeries2.default, - filter: _filter2.default, - filterLimit: _filterLimit2.default, - filterSeries: _filterSeries2.default, - forever: _forever2.default, - groupBy: _groupBy2.default, - groupByLimit: _groupByLimit2.default, - groupBySeries: _groupBySeries2.default, - log: _log2.default, - map: _map2.default, - mapLimit: _mapLimit2.default, - mapSeries: _mapSeries2.default, - mapValues: _mapValues2.default, - mapValuesLimit: _mapValuesLimit2.default, - mapValuesSeries: _mapValuesSeries2.default, - memoize: _memoize2.default, - nextTick: _nextTick2.default, - parallel: _parallel2.default, - parallelLimit: _parallelLimit2.default, - priorityQueue: _priorityQueue2.default, - queue: _queue2.default, - race: _race2.default, - reduce: _reduce2.default, - reduceRight: _reduceRight2.default, - reflect: _reflect2.default, - reflectAll: _reflectAll2.default, - reject: _reject2.default, - rejectLimit: _rejectLimit2.default, - rejectSeries: _rejectSeries2.default, - retry: _retry2.default, - retryable: _retryable2.default, - seq: _seq2.default, - series: _series2.default, - setImmediate: _setImmediate2.default, - some: _some2.default, - someLimit: _someLimit2.default, - someSeries: _someSeries2.default, - sortBy: _sortBy2.default, - timeout: _timeout2.default, - times: _times2.default, - timesLimit: _timesLimit2.default, - timesSeries: _timesSeries2.default, - transform: _transform2.default, - tryEach: _tryEach2.default, - unmemoize: _unmemoize2.default, - until: _until2.default, - waterfall: _waterfall2.default, - whilst: _whilst2.default, - - // aliases - all: _every2.default, - allLimit: _everyLimit2.default, - allSeries: _everySeries2.default, - any: _some2.default, - anyLimit: _someLimit2.default, - anySeries: _someSeries2.default, - find: _detect2.default, - findLimit: _detectLimit2.default, - findSeries: _detectSeries2.default, - forEach: _each2.default, - forEachSeries: _eachSeries2.default, - forEachLimit: _eachLimit2.default, - forEachOf: _eachOf2.default, - forEachOfSeries: _eachOfSeries2.default, - forEachOfLimit: _eachOfLimit2.default, - inject: _reduce2.default, - foldl: _reduce2.default, - foldr: _reduceRight2.default, - select: _filter2.default, - selectLimit: _filterLimit2.default, - selectSeries: _filterSeries2.default, - wrapSync: _asyncify2.default -}; /** - * An "async function" in the context of Async is an asynchronous function with - * a variable number of parameters, with the final parameter being a callback. - * (`function (arg1, arg2, ..., callback) {}`) - * The final callback is of the form `callback(err, results...)`, which must be - * called once the function is completed. The callback should be called with a - * Error as its first argument to signal that an error occurred. - * Otherwise, if no error occurred, it should be called with `null` as the first - * argument, and any additional `result` arguments that may apply, to signal - * successful completion. - * The callback must be called exactly once, ideally on a later tick of the - * JavaScript event loop. - * - * This type of function is also referred to as a "Node-style async function", - * or a "continuation passing-style function" (CPS). Most of the methods of this - * library are themselves CPS/Node-style async functions, or functions that - * return CPS/Node-style async functions. - * - * Wherever we accept a Node-style async function, we also directly accept an - * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. - * In this case, the `async` function will not be passed a final callback - * argument, and any thrown error will be used as the `err` argument of the - * implicit callback, and the return value will be used as the `result` value. - * (i.e. a `rejected` of the returned Promise becomes the `err` callback - * argument, and a `resolved` value becomes the `result`.) - * - * Note, due to JavaScript limitations, we can only detect native `async` - * functions and not transpilied implementations. - * Your environment must have `async`/`await` support for this to work. - * (e.g. Node > v7.6, or a recent version of a modern browser). - * If you are using `async` functions through a transpiler (e.g. Babel), you - * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, - * because the `async function` will be compiled to an ordinary function that - * returns a promise. - * - * @typedef {Function} AsyncFunction - * @static - */ - -/** - * Async is a utility module which provides straight-forward, powerful functions - * for working with asynchronous JavaScript. Although originally designed for - * use with [Node.js](http://nodejs.org) and installable via - * `npm install --save async`, it can also be used directly in the browser. - * @module async - * @see AsyncFunction - */ - -/** - * A collection of `async` functions for manipulating collections, such as - * arrays and objects. - * @module Collections - */ - -/** - * A collection of `async` functions for controlling the flow through a script. - * @module ControlFlow - */ - -/** - * A collection of `async` utility functions. - * @module Utils - */ - -exports.apply = _apply2.default; -exports.applyEach = _applyEach2.default; -exports.applyEachSeries = _applyEachSeries2.default; -exports.asyncify = _asyncify2.default; -exports.auto = _auto2.default; -exports.autoInject = _autoInject2.default; -exports.cargo = _cargo2.default; -exports.compose = _compose2.default; -exports.concat = _concat2.default; -exports.concatLimit = _concatLimit2.default; -exports.concatSeries = _concatSeries2.default; -exports.constant = _constant2.default; -exports.detect = _detect2.default; -exports.detectLimit = _detectLimit2.default; -exports.detectSeries = _detectSeries2.default; -exports.dir = _dir2.default; -exports.doDuring = _doDuring2.default; -exports.doUntil = _doUntil2.default; -exports.doWhilst = _doWhilst2.default; -exports.during = _during2.default; -exports.each = _each2.default; -exports.eachLimit = _eachLimit2.default; -exports.eachOf = _eachOf2.default; -exports.eachOfLimit = _eachOfLimit2.default; -exports.eachOfSeries = _eachOfSeries2.default; -exports.eachSeries = _eachSeries2.default; -exports.ensureAsync = _ensureAsync2.default; -exports.every = _every2.default; -exports.everyLimit = _everyLimit2.default; -exports.everySeries = _everySeries2.default; -exports.filter = _filter2.default; -exports.filterLimit = _filterLimit2.default; -exports.filterSeries = _filterSeries2.default; -exports.forever = _forever2.default; -exports.groupBy = _groupBy2.default; -exports.groupByLimit = _groupByLimit2.default; -exports.groupBySeries = _groupBySeries2.default; -exports.log = _log2.default; -exports.map = _map2.default; -exports.mapLimit = _mapLimit2.default; -exports.mapSeries = _mapSeries2.default; -exports.mapValues = _mapValues2.default; -exports.mapValuesLimit = _mapValuesLimit2.default; -exports.mapValuesSeries = _mapValuesSeries2.default; -exports.memoize = _memoize2.default; -exports.nextTick = _nextTick2.default; -exports.parallel = _parallel2.default; -exports.parallelLimit = _parallelLimit2.default; -exports.priorityQueue = _priorityQueue2.default; -exports.queue = _queue2.default; -exports.race = _race2.default; -exports.reduce = _reduce2.default; -exports.reduceRight = _reduceRight2.default; -exports.reflect = _reflect2.default; -exports.reflectAll = _reflectAll2.default; -exports.reject = _reject2.default; -exports.rejectLimit = _rejectLimit2.default; -exports.rejectSeries = _rejectSeries2.default; -exports.retry = _retry2.default; -exports.retryable = _retryable2.default; -exports.seq = _seq2.default; -exports.series = _series2.default; -exports.setImmediate = _setImmediate2.default; -exports.some = _some2.default; -exports.someLimit = _someLimit2.default; -exports.someSeries = _someSeries2.default; -exports.sortBy = _sortBy2.default; -exports.timeout = _timeout2.default; -exports.times = _times2.default; -exports.timesLimit = _timesLimit2.default; -exports.timesSeries = _timesSeries2.default; -exports.transform = _transform2.default; -exports.tryEach = _tryEach2.default; -exports.unmemoize = _unmemoize2.default; -exports.until = _until2.default; -exports.waterfall = _waterfall2.default; -exports.whilst = _whilst2.default; -exports.all = _every2.default; -exports.allLimit = _everyLimit2.default; -exports.allSeries = _everySeries2.default; -exports.any = _some2.default; -exports.anyLimit = _someLimit2.default; -exports.anySeries = _someSeries2.default; -exports.find = _detect2.default; -exports.findLimit = _detectLimit2.default; -exports.findSeries = _detectSeries2.default; -exports.forEach = _each2.default; -exports.forEachSeries = _eachSeries2.default; -exports.forEachLimit = _eachLimit2.default; -exports.forEachOf = _eachOf2.default; -exports.forEachOfSeries = _eachOfSeries2.default; -exports.forEachOfLimit = _eachOfLimit2.default; -exports.inject = _reduce2.default; -exports.foldl = _reduce2.default; -exports.foldr = _reduceRight2.default; -exports.select = _filter2.default; -exports.selectLimit = _filterLimit2.default; -exports.selectSeries = _filterSeries2.default; -exports.wrapSync = _asyncify2.default;
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/inject.js b/node_modules/webpack/node_modules/async/inject.js deleted file mode 100644 index 3fb8019e4..000000000 --- a/node_modules/webpack/node_modules/async/inject.js +++ /dev/null @@ -1,78 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = reduce; - -var _eachOfSeries = require('./eachOfSeries'); - -var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _once = require('./internal/once'); - -var _once2 = _interopRequireDefault(_once); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Reduces `coll` into a single value using an async `iteratee` to return each - * successive step. `memo` is the initial state of the reduction. This function - * only operates in series. - * - * For performance reasons, it may make sense to split a call to this function - * into a parallel map, and then use the normal `Array.prototype.reduce` on the - * results. This function is for situations where each step in the reduction - * needs to be async; if you can get the data before reducing it, then it's - * probably a good idea to do so. - * - * @name reduce - * @static - * @memberOf module:Collections - * @method - * @alias inject - * @alias foldl - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {*} memo - The initial state of the reduction. - * @param {AsyncFunction} iteratee - A function applied to each item in the - * array to produce the next step in the reduction. - * The `iteratee` should complete with the next state of the reduction. - * If the iteratee complete with an error, the reduction is stopped and the - * main `callback` is immediately called with the error. - * Invoked with (memo, item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result is the reduced value. Invoked with - * (err, result). - * @example - * - * async.reduce([1,2,3], 0, function(memo, item, callback) { - * // pointless async: - * process.nextTick(function() { - * callback(null, memo + item) - * }); - * }, function(err, result) { - * // result is now equal to the last value of memo, which is 6 - * }); - */ -function reduce(coll, memo, iteratee, callback) { - callback = (0, _once2.default)(callback || _noop2.default); - var _iteratee = (0, _wrapAsync2.default)(iteratee); - (0, _eachOfSeries2.default)(coll, function (x, i, callback) { - _iteratee(memo, x, function (err, v) { - memo = v; - callback(err); - }); - }, function (err) { - callback(err, memo); - }); -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/internal/DoublyLinkedList.js b/node_modules/webpack/node_modules/async/internal/DoublyLinkedList.js deleted file mode 100644 index 7e71728e2..000000000 --- a/node_modules/webpack/node_modules/async/internal/DoublyLinkedList.js +++ /dev/null @@ -1,88 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = DLL; -// Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation -// used for queues. This implementation assumes that the node provided by the user can be modified -// to adjust the next and last properties. We implement only the minimal functionality -// for queue support. -function DLL() { - this.head = this.tail = null; - this.length = 0; -} - -function setInitial(dll, node) { - dll.length = 1; - dll.head = dll.tail = node; -} - -DLL.prototype.removeLink = function (node) { - if (node.prev) node.prev.next = node.next;else this.head = node.next; - if (node.next) node.next.prev = node.prev;else this.tail = node.prev; - - node.prev = node.next = null; - this.length -= 1; - return node; -}; - -DLL.prototype.empty = function () { - while (this.head) this.shift(); - return this; -}; - -DLL.prototype.insertAfter = function (node, newNode) { - newNode.prev = node; - newNode.next = node.next; - if (node.next) node.next.prev = newNode;else this.tail = newNode; - node.next = newNode; - this.length += 1; -}; - -DLL.prototype.insertBefore = function (node, newNode) { - newNode.prev = node.prev; - newNode.next = node; - if (node.prev) node.prev.next = newNode;else this.head = newNode; - node.prev = newNode; - this.length += 1; -}; - -DLL.prototype.unshift = function (node) { - if (this.head) this.insertBefore(this.head, node);else setInitial(this, node); -}; - -DLL.prototype.push = function (node) { - if (this.tail) this.insertAfter(this.tail, node);else setInitial(this, node); -}; - -DLL.prototype.shift = function () { - return this.head && this.removeLink(this.head); -}; - -DLL.prototype.pop = function () { - return this.tail && this.removeLink(this.tail); -}; - -DLL.prototype.toArray = function () { - var arr = Array(this.length); - var curr = this.head; - for (var idx = 0; idx < this.length; idx++) { - arr[idx] = curr.data; - curr = curr.next; - } - return arr; -}; - -DLL.prototype.remove = function (testFn) { - var curr = this.head; - while (!!curr) { - var next = curr.next; - if (testFn(curr)) { - this.removeLink(curr); - } - curr = next; - } - return this; -}; -module.exports = exports["default"];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/internal/applyEach.js b/node_modules/webpack/node_modules/async/internal/applyEach.js deleted file mode 100644 index 322e03ca7..000000000 --- a/node_modules/webpack/node_modules/async/internal/applyEach.js +++ /dev/null @@ -1,38 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = applyEach; - -var _slice = require('./slice'); - -var _slice2 = _interopRequireDefault(_slice); - -var _initialParams = require('./initialParams'); - -var _initialParams2 = _interopRequireDefault(_initialParams); - -var _wrapAsync = require('./wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function applyEach(eachfn) { - return function (fns /*, ...args*/) { - var args = (0, _slice2.default)(arguments, 1); - var go = (0, _initialParams2.default)(function (args, callback) { - var that = this; - return eachfn(fns, function (fn, cb) { - (0, _wrapAsync2.default)(fn).apply(that, args.concat(cb)); - }, callback); - }); - if (args.length) { - return go.apply(this, args); - } else { - return go; - } - }; -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/internal/breakLoop.js b/node_modules/webpack/node_modules/async/internal/breakLoop.js deleted file mode 100644 index 106505824..000000000 --- a/node_modules/webpack/node_modules/async/internal/breakLoop.js +++ /dev/null @@ -1,9 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -// A temporary value used to identify if the loop should be broken. -// See #1064, #1293 -exports.default = {}; -module.exports = exports["default"];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/internal/consoleFunc.js b/node_modules/webpack/node_modules/async/internal/consoleFunc.js deleted file mode 100644 index 603f48e8e..000000000 --- a/node_modules/webpack/node_modules/async/internal/consoleFunc.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = consoleFunc; - -var _arrayEach = require('lodash/_arrayEach'); - -var _arrayEach2 = _interopRequireDefault(_arrayEach); - -var _slice = require('./slice'); - -var _slice2 = _interopRequireDefault(_slice); - -var _wrapAsync = require('./wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function consoleFunc(name) { - return function (fn /*, ...args*/) { - var args = (0, _slice2.default)(arguments, 1); - args.push(function (err /*, ...args*/) { - var args = (0, _slice2.default)(arguments, 1); - if (typeof console === 'object') { - if (err) { - if (console.error) { - console.error(err); - } - } else if (console[name]) { - (0, _arrayEach2.default)(args, function (x) { - console[name](x); - }); - } - } - }); - (0, _wrapAsync2.default)(fn).apply(null, args); - }; -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/internal/createTester.js b/node_modules/webpack/node_modules/async/internal/createTester.js deleted file mode 100644 index ce96e8b4e..000000000 --- a/node_modules/webpack/node_modules/async/internal/createTester.js +++ /dev/null @@ -1,44 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = _createTester; - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _breakLoop = require('./breakLoop'); - -var _breakLoop2 = _interopRequireDefault(_breakLoop); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _createTester(check, getResult) { - return function (eachfn, arr, iteratee, cb) { - cb = cb || _noop2.default; - var testPassed = false; - var testResult; - eachfn(arr, function (value, _, callback) { - iteratee(value, function (err, result) { - if (err) { - callback(err); - } else if (check(result) && !testResult) { - testPassed = true; - testResult = getResult(true, value); - callback(null, _breakLoop2.default); - } else { - callback(); - } - }); - }, function (err) { - if (err) { - cb(err); - } else { - cb(null, testPassed ? testResult : getResult(false)); - } - }); - }; -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/internal/doLimit.js b/node_modules/webpack/node_modules/async/internal/doLimit.js deleted file mode 100644 index 963c6088f..000000000 --- a/node_modules/webpack/node_modules/async/internal/doLimit.js +++ /dev/null @@ -1,12 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = doLimit; -function doLimit(fn, limit) { - return function (iterable, iteratee, callback) { - return fn(iterable, limit, iteratee, callback); - }; -} -module.exports = exports["default"];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/internal/doParallel.js b/node_modules/webpack/node_modules/async/internal/doParallel.js deleted file mode 100644 index bb402077c..000000000 --- a/node_modules/webpack/node_modules/async/internal/doParallel.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = doParallel; - -var _eachOf = require('../eachOf'); - -var _eachOf2 = _interopRequireDefault(_eachOf); - -var _wrapAsync = require('./wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function doParallel(fn) { - return function (obj, iteratee, callback) { - return fn(_eachOf2.default, obj, (0, _wrapAsync2.default)(iteratee), callback); - }; -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/internal/doParallelLimit.js b/node_modules/webpack/node_modules/async/internal/doParallelLimit.js deleted file mode 100644 index a7e963d53..000000000 --- a/node_modules/webpack/node_modules/async/internal/doParallelLimit.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = doParallelLimit; - -var _eachOfLimit = require('./eachOfLimit'); - -var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); - -var _wrapAsync = require('./wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function doParallelLimit(fn) { - return function (obj, limit, iteratee, callback) { - return fn((0, _eachOfLimit2.default)(limit), obj, (0, _wrapAsync2.default)(iteratee), callback); - }; -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/internal/eachOfLimit.js b/node_modules/webpack/node_modules/async/internal/eachOfLimit.js deleted file mode 100644 index e4c74bb12..000000000 --- a/node_modules/webpack/node_modules/async/internal/eachOfLimit.js +++ /dev/null @@ -1,71 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = _eachOfLimit; - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _once = require('./once'); - -var _once2 = _interopRequireDefault(_once); - -var _iterator = require('./iterator'); - -var _iterator2 = _interopRequireDefault(_iterator); - -var _onlyOnce = require('./onlyOnce'); - -var _onlyOnce2 = _interopRequireDefault(_onlyOnce); - -var _breakLoop = require('./breakLoop'); - -var _breakLoop2 = _interopRequireDefault(_breakLoop); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _eachOfLimit(limit) { - return function (obj, iteratee, callback) { - callback = (0, _once2.default)(callback || _noop2.default); - if (limit <= 0 || !obj) { - return callback(null); - } - var nextElem = (0, _iterator2.default)(obj); - var done = false; - var running = 0; - - function iterateeCallback(err, value) { - running -= 1; - if (err) { - done = true; - callback(err); - } else if (value === _breakLoop2.default || done && running <= 0) { - done = true; - return callback(null); - } else { - replenish(); - } - } - - function replenish() { - while (running < limit && !done) { - var elem = nextElem(); - if (elem === null) { - done = true; - if (running <= 0) { - callback(null); - } - return; - } - running += 1; - iteratee(elem.value, elem.key, (0, _onlyOnce2.default)(iterateeCallback)); - } - } - - replenish(); - }; -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/internal/filter.js b/node_modules/webpack/node_modules/async/internal/filter.js deleted file mode 100644 index 74f398635..000000000 --- a/node_modules/webpack/node_modules/async/internal/filter.js +++ /dev/null @@ -1,75 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = _filter; - -var _arrayMap = require('lodash/_arrayMap'); - -var _arrayMap2 = _interopRequireDefault(_arrayMap); - -var _isArrayLike = require('lodash/isArrayLike'); - -var _isArrayLike2 = _interopRequireDefault(_isArrayLike); - -var _baseProperty = require('lodash/_baseProperty'); - -var _baseProperty2 = _interopRequireDefault(_baseProperty); - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _wrapAsync = require('./wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function filterArray(eachfn, arr, iteratee, callback) { - var truthValues = new Array(arr.length); - eachfn(arr, function (x, index, callback) { - iteratee(x, function (err, v) { - truthValues[index] = !!v; - callback(err); - }); - }, function (err) { - if (err) return callback(err); - var results = []; - for (var i = 0; i < arr.length; i++) { - if (truthValues[i]) results.push(arr[i]); - } - callback(null, results); - }); -} - -function filterGeneric(eachfn, coll, iteratee, callback) { - var results = []; - eachfn(coll, function (x, index, callback) { - iteratee(x, function (err, v) { - if (err) { - callback(err); - } else { - if (v) { - results.push({ index: index, value: x }); - } - callback(); - } - }); - }, function (err) { - if (err) { - callback(err); - } else { - callback(null, (0, _arrayMap2.default)(results.sort(function (a, b) { - return a.index - b.index; - }), (0, _baseProperty2.default)('value'))); - } - }); -} - -function _filter(eachfn, coll, iteratee, callback) { - var filter = (0, _isArrayLike2.default)(coll) ? filterArray : filterGeneric; - filter(eachfn, coll, (0, _wrapAsync2.default)(iteratee), callback || _noop2.default); -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/internal/findGetResult.js b/node_modules/webpack/node_modules/async/internal/findGetResult.js deleted file mode 100644 index f8d3fe063..000000000 --- a/node_modules/webpack/node_modules/async/internal/findGetResult.js +++ /dev/null @@ -1,10 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = _findGetResult; -function _findGetResult(v, x) { - return x; -} -module.exports = exports["default"];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/internal/getIterator.js b/node_modules/webpack/node_modules/async/internal/getIterator.js deleted file mode 100644 index 3eadd24d0..000000000 --- a/node_modules/webpack/node_modules/async/internal/getIterator.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -exports.default = function (coll) { - return iteratorSymbol && coll[iteratorSymbol] && coll[iteratorSymbol](); -}; - -var iteratorSymbol = typeof Symbol === 'function' && Symbol.iterator; - -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/internal/initialParams.js b/node_modules/webpack/node_modules/async/internal/initialParams.js deleted file mode 100644 index df02cb1f1..000000000 --- a/node_modules/webpack/node_modules/async/internal/initialParams.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -exports.default = function (fn) { - return function () /*...args, callback*/{ - var args = (0, _slice2.default)(arguments); - var callback = args.pop(); - fn.call(this, args, callback); - }; -}; - -var _slice = require('./slice'); - -var _slice2 = _interopRequireDefault(_slice); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/internal/iterator.js b/node_modules/webpack/node_modules/async/internal/iterator.js deleted file mode 100644 index 3d32942ff..000000000 --- a/node_modules/webpack/node_modules/async/internal/iterator.js +++ /dev/null @@ -1,58 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = iterator; - -var _isArrayLike = require('lodash/isArrayLike'); - -var _isArrayLike2 = _interopRequireDefault(_isArrayLike); - -var _getIterator = require('./getIterator'); - -var _getIterator2 = _interopRequireDefault(_getIterator); - -var _keys = require('lodash/keys'); - -var _keys2 = _interopRequireDefault(_keys); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function createArrayIterator(coll) { - var i = -1; - var len = coll.length; - return function next() { - return ++i < len ? { value: coll[i], key: i } : null; - }; -} - -function createES2015Iterator(iterator) { - var i = -1; - return function next() { - var item = iterator.next(); - if (item.done) return null; - i++; - return { value: item.value, key: i }; - }; -} - -function createObjectIterator(obj) { - var okeys = (0, _keys2.default)(obj); - var i = -1; - var len = okeys.length; - return function next() { - var key = okeys[++i]; - return i < len ? { value: obj[key], key: key } : null; - }; -} - -function iterator(coll) { - if ((0, _isArrayLike2.default)(coll)) { - return createArrayIterator(coll); - } - - var iterator = (0, _getIterator2.default)(coll); - return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/internal/map.js b/node_modules/webpack/node_modules/async/internal/map.js deleted file mode 100644 index f4f2aa594..000000000 --- a/node_modules/webpack/node_modules/async/internal/map.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = _asyncMap; - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _wrapAsync = require('./wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _asyncMap(eachfn, arr, iteratee, callback) { - callback = callback || _noop2.default; - arr = arr || []; - var results = []; - var counter = 0; - var _iteratee = (0, _wrapAsync2.default)(iteratee); - - eachfn(arr, function (value, _, callback) { - var index = counter++; - _iteratee(value, function (err, v) { - results[index] = v; - callback(err); - }); - }, function (err) { - callback(err, results); - }); -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/internal/notId.js b/node_modules/webpack/node_modules/async/internal/notId.js deleted file mode 100644 index 0106c92c0..000000000 --- a/node_modules/webpack/node_modules/async/internal/notId.js +++ /dev/null @@ -1,10 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = notId; -function notId(v) { - return !v; -} -module.exports = exports["default"];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/internal/once.js b/node_modules/webpack/node_modules/async/internal/once.js deleted file mode 100644 index f0c379f75..000000000 --- a/node_modules/webpack/node_modules/async/internal/once.js +++ /dev/null @@ -1,15 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = once; -function once(fn) { - return function () { - if (fn === null) return; - var callFn = fn; - fn = null; - callFn.apply(this, arguments); - }; -} -module.exports = exports["default"];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/internal/onlyOnce.js b/node_modules/webpack/node_modules/async/internal/onlyOnce.js deleted file mode 100644 index f2e3001dc..000000000 --- a/node_modules/webpack/node_modules/async/internal/onlyOnce.js +++ /dev/null @@ -1,15 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = onlyOnce; -function onlyOnce(fn) { - return function () { - if (fn === null) throw new Error("Callback was already called."); - var callFn = fn; - fn = null; - callFn.apply(this, arguments); - }; -} -module.exports = exports["default"];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/internal/parallel.js b/node_modules/webpack/node_modules/async/internal/parallel.js deleted file mode 100644 index c97293b6c..000000000 --- a/node_modules/webpack/node_modules/async/internal/parallel.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = _parallel; - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _isArrayLike = require('lodash/isArrayLike'); - -var _isArrayLike2 = _interopRequireDefault(_isArrayLike); - -var _slice = require('./slice'); - -var _slice2 = _interopRequireDefault(_slice); - -var _wrapAsync = require('./wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _parallel(eachfn, tasks, callback) { - callback = callback || _noop2.default; - var results = (0, _isArrayLike2.default)(tasks) ? [] : {}; - - eachfn(tasks, function (task, key, callback) { - (0, _wrapAsync2.default)(task)(function (err, result) { - if (arguments.length > 2) { - result = (0, _slice2.default)(arguments, 1); - } - results[key] = result; - callback(err); - }); - }, function (err) { - callback(err, results); - }); -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/internal/queue.js b/node_modules/webpack/node_modules/async/internal/queue.js deleted file mode 100644 index 19534a749..000000000 --- a/node_modules/webpack/node_modules/async/internal/queue.js +++ /dev/null @@ -1,204 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = queue; - -var _baseIndexOf = require('lodash/_baseIndexOf'); - -var _baseIndexOf2 = _interopRequireDefault(_baseIndexOf); - -var _isArray = require('lodash/isArray'); - -var _isArray2 = _interopRequireDefault(_isArray); - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _onlyOnce = require('./onlyOnce'); - -var _onlyOnce2 = _interopRequireDefault(_onlyOnce); - -var _setImmediate = require('./setImmediate'); - -var _setImmediate2 = _interopRequireDefault(_setImmediate); - -var _DoublyLinkedList = require('./DoublyLinkedList'); - -var _DoublyLinkedList2 = _interopRequireDefault(_DoublyLinkedList); - -var _wrapAsync = require('./wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function queue(worker, concurrency, payload) { - if (concurrency == null) { - concurrency = 1; - } else if (concurrency === 0) { - throw new Error('Concurrency must not be zero'); - } - - var _worker = (0, _wrapAsync2.default)(worker); - var numRunning = 0; - var workersList = []; - - var processingScheduled = false; - function _insert(data, insertAtFront, callback) { - if (callback != null && typeof callback !== 'function') { - throw new Error('task callback must be a function'); - } - q.started = true; - if (!(0, _isArray2.default)(data)) { - data = [data]; - } - if (data.length === 0 && q.idle()) { - // call drain immediately if there are no tasks - return (0, _setImmediate2.default)(function () { - q.drain(); - }); - } - - for (var i = 0, l = data.length; i < l; i++) { - var item = { - data: data[i], - callback: callback || _noop2.default - }; - - if (insertAtFront) { - q._tasks.unshift(item); - } else { - q._tasks.push(item); - } - } - - if (!processingScheduled) { - processingScheduled = true; - (0, _setImmediate2.default)(function () { - processingScheduled = false; - q.process(); - }); - } - } - - function _next(tasks) { - return function (err) { - numRunning -= 1; - - for (var i = 0, l = tasks.length; i < l; i++) { - var task = tasks[i]; - - var index = (0, _baseIndexOf2.default)(workersList, task, 0); - if (index === 0) { - workersList.shift(); - } else if (index > 0) { - workersList.splice(index, 1); - } - - task.callback.apply(task, arguments); - - if (err != null) { - q.error(err, task.data); - } - } - - if (numRunning <= q.concurrency - q.buffer) { - q.unsaturated(); - } - - if (q.idle()) { - q.drain(); - } - q.process(); - }; - } - - var isProcessing = false; - var q = { - _tasks: new _DoublyLinkedList2.default(), - concurrency: concurrency, - payload: payload, - saturated: _noop2.default, - unsaturated: _noop2.default, - buffer: concurrency / 4, - empty: _noop2.default, - drain: _noop2.default, - error: _noop2.default, - started: false, - paused: false, - push: function (data, callback) { - _insert(data, false, callback); - }, - kill: function () { - q.drain = _noop2.default; - q._tasks.empty(); - }, - unshift: function (data, callback) { - _insert(data, true, callback); - }, - remove: function (testFn) { - q._tasks.remove(testFn); - }, - process: function () { - // Avoid trying to start too many processing operations. This can occur - // when callbacks resolve synchronously (#1267). - if (isProcessing) { - return; - } - isProcessing = true; - while (!q.paused && numRunning < q.concurrency && q._tasks.length) { - var tasks = [], - data = []; - var l = q._tasks.length; - if (q.payload) l = Math.min(l, q.payload); - for (var i = 0; i < l; i++) { - var node = q._tasks.shift(); - tasks.push(node); - workersList.push(node); - data.push(node.data); - } - - numRunning += 1; - - if (q._tasks.length === 0) { - q.empty(); - } - - if (numRunning === q.concurrency) { - q.saturated(); - } - - var cb = (0, _onlyOnce2.default)(_next(tasks)); - _worker(data, cb); - } - isProcessing = false; - }, - length: function () { - return q._tasks.length; - }, - running: function () { - return numRunning; - }, - workersList: function () { - return workersList; - }, - idle: function () { - return q._tasks.length + numRunning === 0; - }, - pause: function () { - q.paused = true; - }, - resume: function () { - if (q.paused === false) { - return; - } - q.paused = false; - (0, _setImmediate2.default)(q.process); - } - }; - return q; -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/internal/reject.js b/node_modules/webpack/node_modules/async/internal/reject.js deleted file mode 100644 index 5dbfcfb15..000000000 --- a/node_modules/webpack/node_modules/async/internal/reject.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = reject; - -var _filter = require('./filter'); - -var _filter2 = _interopRequireDefault(_filter); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function reject(eachfn, arr, iteratee, callback) { - (0, _filter2.default)(eachfn, arr, function (value, cb) { - iteratee(value, function (err, v) { - cb(err, !v); - }); - }, callback); -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/internal/setImmediate.js b/node_modules/webpack/node_modules/async/internal/setImmediate.js deleted file mode 100644 index 3545f2bcd..000000000 --- a/node_modules/webpack/node_modules/async/internal/setImmediate.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.hasNextTick = exports.hasSetImmediate = undefined; -exports.fallback = fallback; -exports.wrap = wrap; - -var _slice = require('./slice'); - -var _slice2 = _interopRequireDefault(_slice); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var hasSetImmediate = exports.hasSetImmediate = typeof setImmediate === 'function' && setImmediate; -var hasNextTick = exports.hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; - -function fallback(fn) { - setTimeout(fn, 0); -} - -function wrap(defer) { - return function (fn /*, ...args*/) { - var args = (0, _slice2.default)(arguments, 1); - defer(function () { - fn.apply(null, args); - }); - }; -} - -var _defer; - -if (hasSetImmediate) { - _defer = setImmediate; -} else if (hasNextTick) { - _defer = process.nextTick; -} else { - _defer = fallback; -} - -exports.default = wrap(_defer);
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/internal/slice.js b/node_modules/webpack/node_modules/async/internal/slice.js deleted file mode 100644 index 56f10c03e..000000000 --- a/node_modules/webpack/node_modules/async/internal/slice.js +++ /dev/null @@ -1,16 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = slice; -function slice(arrayLike, start) { - start = start | 0; - var newLen = Math.max(arrayLike.length - start, 0); - var newArr = Array(newLen); - for (var idx = 0; idx < newLen; idx++) { - newArr[idx] = arrayLike[start + idx]; - } - return newArr; -} -module.exports = exports["default"];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/internal/withoutIndex.js b/node_modules/webpack/node_modules/async/internal/withoutIndex.js deleted file mode 100644 index 2bd35796a..000000000 --- a/node_modules/webpack/node_modules/async/internal/withoutIndex.js +++ /dev/null @@ -1,12 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = _withoutIndex; -function _withoutIndex(iteratee) { - return function (value, index, callback) { - return iteratee(value, callback); - }; -} -module.exports = exports["default"];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/internal/wrapAsync.js b/node_modules/webpack/node_modules/async/internal/wrapAsync.js deleted file mode 100644 index bc6c96668..000000000 --- a/node_modules/webpack/node_modules/async/internal/wrapAsync.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.isAsync = undefined; - -var _asyncify = require('../asyncify'); - -var _asyncify2 = _interopRequireDefault(_asyncify); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var supportsSymbol = typeof Symbol === 'function'; - -function isAsync(fn) { - return supportsSymbol && fn[Symbol.toStringTag] === 'AsyncFunction'; -} - -function wrapAsync(asyncFn) { - return isAsync(asyncFn) ? (0, _asyncify2.default)(asyncFn) : asyncFn; -} - -exports.default = wrapAsync; -exports.isAsync = isAsync;
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/log.js b/node_modules/webpack/node_modules/async/log.js deleted file mode 100644 index c643867bc..000000000 --- a/node_modules/webpack/node_modules/async/log.js +++ /dev/null @@ -1,41 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _consoleFunc = require('./internal/consoleFunc'); - -var _consoleFunc2 = _interopRequireDefault(_consoleFunc); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Logs the result of an `async` function to the `console`. Only works in - * Node.js or in browsers that support `console.log` and `console.error` (such - * as FF and Chrome). If multiple arguments are returned from the async - * function, `console.log` is called on each argument in order. - * - * @name log - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} function - The function you want to eventually apply - * all arguments to. - * @param {...*} arguments... - Any number of arguments to apply to the function. - * @example - * - * // in a module - * var hello = function(name, callback) { - * setTimeout(function() { - * callback(null, 'hello ' + name); - * }, 1000); - * }; - * - * // in the node repl - * node> async.log(hello, 'world'); - * 'hello world' - */ -exports.default = (0, _consoleFunc2.default)('log'); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/map.js b/node_modules/webpack/node_modules/async/map.js deleted file mode 100644 index 67c9cda93..000000000 --- a/node_modules/webpack/node_modules/async/map.js +++ /dev/null @@ -1,54 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _doParallel = require('./internal/doParallel'); - -var _doParallel2 = _interopRequireDefault(_doParallel); - -var _map = require('./internal/map'); - -var _map2 = _interopRequireDefault(_map); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Produces a new collection of values by mapping each value in `coll` through - * the `iteratee` function. The `iteratee` is called with an item from `coll` - * and a callback for when it has finished processing. Each of these callback - * takes 2 arguments: an `error`, and the transformed item from `coll`. If - * `iteratee` passes an error to its callback, the main `callback` (for the - * `map` function) is immediately called with the error. - * - * Note, that since this function applies the `iteratee` to each item in - * parallel, there is no guarantee that the `iteratee` functions will complete - * in order. However, the results array will be in the same order as the - * original `coll`. - * - * If `map` is passed an Object, the results will be an Array. The results - * will roughly be in the order of the original Objects' keys (but this can - * vary across JavaScript engines). - * - * @name map - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with the transformed item. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Results is an Array of the - * transformed items from the `coll`. Invoked with (err, results). - * @example - * - * async.map(['file1','file2','file3'], fs.stat, function(err, results) { - * // results is now an array of stats for each file - * }); - */ -exports.default = (0, _doParallel2.default)(_map2.default); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/mapLimit.js b/node_modules/webpack/node_modules/async/mapLimit.js deleted file mode 100644 index c8b60d8dc..000000000 --- a/node_modules/webpack/node_modules/async/mapLimit.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _doParallelLimit = require('./internal/doParallelLimit'); - -var _doParallelLimit2 = _interopRequireDefault(_doParallelLimit); - -var _map = require('./internal/map'); - -var _map2 = _interopRequireDefault(_map); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time. - * - * @name mapLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.map]{@link module:Collections.map} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with the transformed item. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Results is an array of the - * transformed items from the `coll`. Invoked with (err, results). - */ -exports.default = (0, _doParallelLimit2.default)(_map2.default); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/mapSeries.js b/node_modules/webpack/node_modules/async/mapSeries.js deleted file mode 100644 index 61b42d01b..000000000 --- a/node_modules/webpack/node_modules/async/mapSeries.js +++ /dev/null @@ -1,36 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _mapLimit = require('./mapLimit'); - -var _mapLimit2 = _interopRequireDefault(_mapLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time. - * - * @name mapSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.map]{@link module:Collections.map} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with the transformed item. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Results is an array of the - * transformed items from the `coll`. Invoked with (err, results). - */ -exports.default = (0, _doLimit2.default)(_mapLimit2.default, 1); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/mapValues.js b/node_modules/webpack/node_modules/async/mapValues.js deleted file mode 100644 index 3d838ca1e..000000000 --- a/node_modules/webpack/node_modules/async/mapValues.js +++ /dev/null @@ -1,63 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _mapValuesLimit = require('./mapValuesLimit'); - -var _mapValuesLimit2 = _interopRequireDefault(_mapValuesLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * A relative of [`map`]{@link module:Collections.map}, designed for use with objects. - * - * Produces a new Object by mapping each value of `obj` through the `iteratee` - * function. The `iteratee` is called each `value` and `key` from `obj` and a - * callback for when it has finished processing. Each of these callbacks takes - * two arguments: an `error`, and the transformed item from `obj`. If `iteratee` - * passes an error to its callback, the main `callback` (for the `mapValues` - * function) is immediately called with the error. - * - * Note, the order of the keys in the result is not guaranteed. The keys will - * be roughly in the order they complete, (but this is very engine-specific) - * - * @name mapValues - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Object} obj - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each value and key - * in `coll`. - * The iteratee should complete with the transformed value as its result. - * Invoked with (value, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. `result` is a new object consisting - * of each key from `obj`, with each transformed value on the right-hand side. - * Invoked with (err, result). - * @example - * - * async.mapValues({ - * f1: 'file1', - * f2: 'file2', - * f3: 'file3' - * }, function (file, key, callback) { - * fs.stat(file, callback); - * }, function(err, result) { - * // result is now a map of stats for each file, e.g. - * // { - * // f1: [stats for file1], - * // f2: [stats for file2], - * // f3: [stats for file3] - * // } - * }); - */ - -exports.default = (0, _doLimit2.default)(_mapValuesLimit2.default, Infinity); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/mapValuesLimit.js b/node_modules/webpack/node_modules/async/mapValuesLimit.js deleted file mode 100644 index 912a8b522..000000000 --- a/node_modules/webpack/node_modules/async/mapValuesLimit.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = mapValuesLimit; - -var _eachOfLimit = require('./eachOfLimit'); - -var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _once = require('./internal/once'); - -var _once2 = _interopRequireDefault(_once); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a - * time. - * - * @name mapValuesLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.mapValues]{@link module:Collections.mapValues} - * @category Collection - * @param {Object} obj - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - A function to apply to each value and key - * in `coll`. - * The iteratee should complete with the transformed value as its result. - * Invoked with (value, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. `result` is a new object consisting - * of each key from `obj`, with each transformed value on the right-hand side. - * Invoked with (err, result). - */ -function mapValuesLimit(obj, limit, iteratee, callback) { - callback = (0, _once2.default)(callback || _noop2.default); - var newObj = {}; - var _iteratee = (0, _wrapAsync2.default)(iteratee); - (0, _eachOfLimit2.default)(obj, limit, function (val, key, next) { - _iteratee(val, key, function (err, result) { - if (err) return next(err); - newObj[key] = result; - next(); - }); - }, function (err) { - callback(err, newObj); - }); -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/mapValuesSeries.js b/node_modules/webpack/node_modules/async/mapValuesSeries.js deleted file mode 100644 index b378c4a1a..000000000 --- a/node_modules/webpack/node_modules/async/mapValuesSeries.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _mapValuesLimit = require('./mapValuesLimit'); - -var _mapValuesLimit2 = _interopRequireDefault(_mapValuesLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time. - * - * @name mapValuesSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.mapValues]{@link module:Collections.mapValues} - * @category Collection - * @param {Object} obj - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each value and key - * in `coll`. - * The iteratee should complete with the transformed value as its result. - * Invoked with (value, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. `result` is a new object consisting - * of each key from `obj`, with each transformed value on the right-hand side. - * Invoked with (err, result). - */ -exports.default = (0, _doLimit2.default)(_mapValuesLimit2.default, 1); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/memoize.js b/node_modules/webpack/node_modules/async/memoize.js deleted file mode 100644 index 1f2b56691..000000000 --- a/node_modules/webpack/node_modules/async/memoize.js +++ /dev/null @@ -1,101 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = memoize; - -var _identity = require('lodash/identity'); - -var _identity2 = _interopRequireDefault(_identity); - -var _slice = require('./internal/slice'); - -var _slice2 = _interopRequireDefault(_slice); - -var _setImmediate = require('./internal/setImmediate'); - -var _setImmediate2 = _interopRequireDefault(_setImmediate); - -var _initialParams = require('./internal/initialParams'); - -var _initialParams2 = _interopRequireDefault(_initialParams); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function has(obj, key) { - return key in obj; -} - -/** - * Caches the results of an async function. When creating a hash to store - * function results against, the callback is omitted from the hash and an - * optional hash function can be used. - * - * If no hash function is specified, the first argument is used as a hash key, - * which may work reasonably if it is a string or a data type that converts to a - * distinct string. Note that objects and arrays will not behave reasonably. - * Neither will cases where the other arguments are significant. In such cases, - * specify your own hash function. - * - * The cache of results is exposed as the `memo` property of the function - * returned by `memoize`. - * - * @name memoize - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} fn - The async function to proxy and cache results from. - * @param {Function} hasher - An optional function for generating a custom hash - * for storing results. It has all the arguments applied to it apart from the - * callback, and must be synchronous. - * @returns {AsyncFunction} a memoized version of `fn` - * @example - * - * var slow_fn = function(name, callback) { - * // do something - * callback(null, result); - * }; - * var fn = async.memoize(slow_fn); - * - * // fn can now be used as if it were slow_fn - * fn('some name', function() { - * // callback - * }); - */ -function memoize(fn, hasher) { - var memo = Object.create(null); - var queues = Object.create(null); - hasher = hasher || _identity2.default; - var _fn = (0, _wrapAsync2.default)(fn); - var memoized = (0, _initialParams2.default)(function memoized(args, callback) { - var key = hasher.apply(null, args); - if (has(memo, key)) { - (0, _setImmediate2.default)(function () { - callback.apply(null, memo[key]); - }); - } else if (has(queues, key)) { - queues[key].push(callback); - } else { - queues[key] = [callback]; - _fn.apply(null, args.concat(function () /*args*/{ - var args = (0, _slice2.default)(arguments); - memo[key] = args; - var q = queues[key]; - delete queues[key]; - for (var i = 0, l = q.length; i < l; i++) { - q[i].apply(null, args); - } - })); - } - }); - memoized.memo = memo; - memoized.unmemoized = fn; - return memoized; -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/nextTick.js b/node_modules/webpack/node_modules/async/nextTick.js deleted file mode 100644 index 826495d9c..000000000 --- a/node_modules/webpack/node_modules/async/nextTick.js +++ /dev/null @@ -1,51 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _setImmediate = require('./internal/setImmediate'); - -/** - * Calls `callback` on a later loop around the event loop. In Node.js this just - * calls `process.nextTicl`. In the browser it will use `setImmediate` if - * available, otherwise `setTimeout(callback, 0)`, which means other higher - * priority events may precede the execution of `callback`. - * - * This is used internally for browser-compatibility purposes. - * - * @name nextTick - * @static - * @memberOf module:Utils - * @method - * @see [async.setImmediate]{@link module:Utils.setImmediate} - * @category Util - * @param {Function} callback - The function to call on a later loop around - * the event loop. Invoked with (args...). - * @param {...*} args... - any number of additional arguments to pass to the - * callback on the next tick. - * @example - * - * var call_order = []; - * async.nextTick(function() { - * call_order.push('two'); - * // call_order now equals ['one','two'] - * }); - * call_order.push('one'); - * - * async.setImmediate(function (a, b, c) { - * // a, b, and c equal 1, 2, and 3 - * }, 1, 2, 3); - */ -var _defer; - -if (_setImmediate.hasNextTick) { - _defer = process.nextTick; -} else if (_setImmediate.hasSetImmediate) { - _defer = setImmediate; -} else { - _defer = _setImmediate.fallback; -} - -exports.default = (0, _setImmediate.wrap)(_defer); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/package.json b/node_modules/webpack/node_modules/async/package.json deleted file mode 100644 index f672e7dfe..000000000 --- a/node_modules/webpack/node_modules/async/package.json +++ /dev/null @@ -1,83 +0,0 @@ -{ - "name": "async", - "description": "Higher-order functions and common patterns for asynchronous code", - "version": "2.6.0", - "main": "dist/async.js", - "author": "Caolan McMahon", - "homepage": "https://caolan.github.io/async/", - "repository": { - "type": "git", - "url": "https://github.com/caolan/async.git" - }, - "bugs": { - "url": "https://github.com/caolan/async/issues" - }, - "keywords": [ - "async", - "callback", - "module", - "utility" - ], - "dependencies": { - "lodash": "^4.14.0" - }, - "devDependencies": { - "babel-cli": "^6.24.0", - "babel-core": "^6.24.0", - "babel-plugin-add-module-exports": "^0.2.1", - "babel-plugin-istanbul": "^2.0.1", - "babel-plugin-transform-es2015-modules-commonjs": "^6.3.16", - "babel-preset-es2015": "^6.3.13", - "babel-preset-es2017": "^6.22.0", - "babelify": "^7.2.0", - "benchmark": "^2.1.1", - "bluebird": "^3.4.6", - "chai": "^3.1.0", - "cheerio": "^0.22.0", - "coveralls": "^2.11.2", - "es6-promise": "^2.3.0", - "eslint": "^2.13.1", - "fs-extra": "^0.26.7", - "gh-pages-deploy": "^0.4.2", - "jsdoc": "^3.4.0", - "karma": "^1.3.0", - "karma-browserify": "^5.1.0", - "karma-firefox-launcher": "^1.0.0", - "karma-mocha": "^1.2.0", - "karma-mocha-reporter": "^2.2.0", - "mocha": "^3.1.2", - "native-promise-only": "^0.8.0-a", - "nyc": "^7.0.0", - "recursive-readdir": "^1.3.0", - "rimraf": "^2.5.0", - "rollup": "^0.36.3", - "rollup-plugin-node-resolve": "^2.0.0", - "rollup-plugin-npm": "^2.0.0", - "rsvp": "^3.0.18", - "semver": "^4.3.6", - "uglify-js": "~2.7.3", - "vinyl-buffer": "^1.0.0", - "vinyl-source-stream": "^1.1.0", - "watchify": "^3.7.0", - "yargs": "~3.9.1" - }, - "scripts": { - "coverage": "nyc npm run mocha-node-test -- --grep @nycinvalid --invert", - "coveralls": "npm run coverage && nyc report --reporter=text-lcov | coveralls", - "jsdoc": "jsdoc -c ./support/jsdoc/jsdoc.json && node support/jsdoc/jsdoc-fix-html.js", - "lint": "eslint lib/ mocha_test/ perf/memory.js perf/suites.js perf/benchmark.js support/build/ support/*.js karma.conf.js", - "mocha-browser-test": "karma start", - "mocha-node-test": "mocha mocha_test/ --compilers js:babel-core/register", - "mocha-test": "npm run mocha-node-test && npm run mocha-browser-test", - "test": "npm run lint && npm run mocha-node-test" - }, - "license": "MIT", - "gh-pages-deploy": { - "staticpath": "docs" - }, - "nyc": { - "exclude": [ - "mocha_test" - ] - } -}
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/parallel.js b/node_modules/webpack/node_modules/async/parallel.js deleted file mode 100644 index da28a4def..000000000 --- a/node_modules/webpack/node_modules/async/parallel.js +++ /dev/null @@ -1,90 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = parallelLimit; - -var _eachOf = require('./eachOf'); - -var _eachOf2 = _interopRequireDefault(_eachOf); - -var _parallel = require('./internal/parallel'); - -var _parallel2 = _interopRequireDefault(_parallel); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Run the `tasks` collection of functions in parallel, without waiting until - * the previous function has completed. If any of the functions pass an error to - * its callback, the main `callback` is immediately called with the value of the - * error. Once the `tasks` have completed, the results are passed to the final - * `callback` as an array. - * - * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about - * parallel execution of code. If your tasks do not use any timers or perform - * any I/O, they will actually be executed in series. Any synchronous setup - * sections for each task will happen one after the other. JavaScript remains - * single-threaded. - * - * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the - * execution of other tasks when a task fails. - * - * It is also possible to use an object instead of an array. Each property will - * be run as a function and the results will be passed to the final `callback` - * as an object instead of an array. This can be a more readable way of handling - * results from {@link async.parallel}. - * - * @name parallel - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|Object} tasks - A collection of - * [async functions]{@link AsyncFunction} to run. - * Each async function can complete with any number of optional `result` values. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed successfully. This function gets a results array - * (or object) containing all the result arguments passed to the task callbacks. - * Invoked with (err, results). - * - * @example - * async.parallel([ - * function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * setTimeout(function() { - * callback(null, 'two'); - * }, 100); - * } - * ], - * // optional callback - * function(err, results) { - * // the results array will equal ['one','two'] even though - * // the second function had a shorter timeout. - * }); - * - * // an example using an object instead of an array - * async.parallel({ - * one: function(callback) { - * setTimeout(function() { - * callback(null, 1); - * }, 200); - * }, - * two: function(callback) { - * setTimeout(function() { - * callback(null, 2); - * }, 100); - * } - * }, function(err, results) { - * // results is now equals to: {one: 1, two: 2} - * }); - */ -function parallelLimit(tasks, callback) { - (0, _parallel2.default)(_eachOf2.default, tasks, callback); -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/parallelLimit.js b/node_modules/webpack/node_modules/async/parallelLimit.js deleted file mode 100644 index a026526f4..000000000 --- a/node_modules/webpack/node_modules/async/parallelLimit.js +++ /dev/null @@ -1,40 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = parallelLimit; - -var _eachOfLimit = require('./internal/eachOfLimit'); - -var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); - -var _parallel = require('./internal/parallel'); - -var _parallel2 = _interopRequireDefault(_parallel); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a - * time. - * - * @name parallelLimit - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.parallel]{@link module:ControlFlow.parallel} - * @category Control Flow - * @param {Array|Iterable|Object} tasks - A collection of - * [async functions]{@link AsyncFunction} to run. - * Each async function can complete with any number of optional `result` values. - * @param {number} limit - The maximum number of async operations at a time. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed successfully. This function gets a results array - * (or object) containing all the result arguments passed to the task callbacks. - * Invoked with (err, results). - */ -function parallelLimit(tasks, limit, callback) { - (0, _parallel2.default)((0, _eachOfLimit2.default)(limit), tasks, callback); -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/priorityQueue.js b/node_modules/webpack/node_modules/async/priorityQueue.js deleted file mode 100644 index 3a5f023e5..000000000 --- a/node_modules/webpack/node_modules/async/priorityQueue.js +++ /dev/null @@ -1,98 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -exports.default = function (worker, concurrency) { - // Start with a normal queue - var q = (0, _queue2.default)(worker, concurrency); - - // Override push to accept second parameter representing priority - q.push = function (data, priority, callback) { - if (callback == null) callback = _noop2.default; - if (typeof callback !== 'function') { - throw new Error('task callback must be a function'); - } - q.started = true; - if (!(0, _isArray2.default)(data)) { - data = [data]; - } - if (data.length === 0) { - // call drain immediately if there are no tasks - return (0, _setImmediate2.default)(function () { - q.drain(); - }); - } - - priority = priority || 0; - var nextNode = q._tasks.head; - while (nextNode && priority >= nextNode.priority) { - nextNode = nextNode.next; - } - - for (var i = 0, l = data.length; i < l; i++) { - var item = { - data: data[i], - priority: priority, - callback: callback - }; - - if (nextNode) { - q._tasks.insertBefore(nextNode, item); - } else { - q._tasks.push(item); - } - } - (0, _setImmediate2.default)(q.process); - }; - - // Remove unshift function - delete q.unshift; - - return q; -}; - -var _isArray = require('lodash/isArray'); - -var _isArray2 = _interopRequireDefault(_isArray); - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _setImmediate = require('./setImmediate'); - -var _setImmediate2 = _interopRequireDefault(_setImmediate); - -var _queue = require('./queue'); - -var _queue2 = _interopRequireDefault(_queue); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -module.exports = exports['default']; - -/** - * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and - * completed in ascending priority order. - * - * @name priorityQueue - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.queue]{@link module:ControlFlow.queue} - * @category Control Flow - * @param {AsyncFunction} worker - An async function for processing a queued task. - * If you want to handle errors from an individual task, pass a callback to - * `q.push()`. - * Invoked with (task, callback). - * @param {number} concurrency - An `integer` for determining how many `worker` - * functions should be run in parallel. If omitted, the concurrency defaults to - * `1`. If the concurrency is `0`, an error is thrown. - * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are two - * differences between `queue` and `priorityQueue` objects: - * * `push(task, priority, [callback])` - `priority` should be a number. If an - * array of `tasks` is given, all tasks will be assigned the same priority. - * * The `unshift` method was removed. - */
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/queue.js b/node_modules/webpack/node_modules/async/queue.js deleted file mode 100644 index 0ca8ba2bb..000000000 --- a/node_modules/webpack/node_modules/async/queue.js +++ /dev/null @@ -1,130 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -exports.default = function (worker, concurrency) { - var _worker = (0, _wrapAsync2.default)(worker); - return (0, _queue2.default)(function (items, cb) { - _worker(items[0], cb); - }, concurrency, 1); -}; - -var _queue = require('./internal/queue'); - -var _queue2 = _interopRequireDefault(_queue); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -module.exports = exports['default']; - -/** - * A queue of tasks for the worker function to complete. - * @typedef {Object} QueueObject - * @memberOf module:ControlFlow - * @property {Function} length - a function returning the number of items - * waiting to be processed. Invoke with `queue.length()`. - * @property {boolean} started - a boolean indicating whether or not any - * items have been pushed and processed by the queue. - * @property {Function} running - a function returning the number of items - * currently being processed. Invoke with `queue.running()`. - * @property {Function} workersList - a function returning the array of items - * currently being processed. Invoke with `queue.workersList()`. - * @property {Function} idle - a function returning false if there are items - * waiting or being processed, or true if not. Invoke with `queue.idle()`. - * @property {number} concurrency - an integer for determining how many `worker` - * functions should be run in parallel. This property can be changed after a - * `queue` is created to alter the concurrency on-the-fly. - * @property {Function} push - add a new task to the `queue`. Calls `callback` - * once the `worker` has finished processing the task. Instead of a single task, - * a `tasks` array can be submitted. The respective callback is used for every - * task in the list. Invoke with `queue.push(task, [callback])`, - * @property {Function} unshift - add a new task to the front of the `queue`. - * Invoke with `queue.unshift(task, [callback])`. - * @property {Function} remove - remove items from the queue that match a test - * function. The test function will be passed an object with a `data` property, - * and a `priority` property, if this is a - * [priorityQueue]{@link module:ControlFlow.priorityQueue} object. - * Invoked with `queue.remove(testFn)`, where `testFn` is of the form - * `function ({data, priority}) {}` and returns a Boolean. - * @property {Function} saturated - a callback that is called when the number of - * running workers hits the `concurrency` limit, and further tasks will be - * queued. - * @property {Function} unsaturated - a callback that is called when the number - * of running workers is less than the `concurrency` & `buffer` limits, and - * further tasks will not be queued. - * @property {number} buffer - A minimum threshold buffer in order to say that - * the `queue` is `unsaturated`. - * @property {Function} empty - a callback that is called when the last item - * from the `queue` is given to a `worker`. - * @property {Function} drain - a callback that is called when the last item - * from the `queue` has returned from the `worker`. - * @property {Function} error - a callback that is called when a task errors. - * Has the signature `function(error, task)`. - * @property {boolean} paused - a boolean for determining whether the queue is - * in a paused state. - * @property {Function} pause - a function that pauses the processing of tasks - * until `resume()` is called. Invoke with `queue.pause()`. - * @property {Function} resume - a function that resumes the processing of - * queued tasks when the queue is paused. Invoke with `queue.resume()`. - * @property {Function} kill - a function that removes the `drain` callback and - * empties remaining tasks from the queue forcing it to go idle. No more tasks - * should be pushed to the queue after calling this function. Invoke with `queue.kill()`. - */ - -/** - * Creates a `queue` object with the specified `concurrency`. Tasks added to the - * `queue` are processed in parallel (up to the `concurrency` limit). If all - * `worker`s are in progress, the task is queued until one becomes available. - * Once a `worker` completes a `task`, that `task`'s callback is called. - * - * @name queue - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {AsyncFunction} worker - An async function for processing a queued task. - * If you want to handle errors from an individual task, pass a callback to - * `q.push()`. Invoked with (task, callback). - * @param {number} [concurrency=1] - An `integer` for determining how many - * `worker` functions should be run in parallel. If omitted, the concurrency - * defaults to `1`. If the concurrency is `0`, an error is thrown. - * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can - * attached as certain properties to listen for specific events during the - * lifecycle of the queue. - * @example - * - * // create a queue object with concurrency 2 - * var q = async.queue(function(task, callback) { - * console.log('hello ' + task.name); - * callback(); - * }, 2); - * - * // assign a callback - * q.drain = function() { - * console.log('all items have been processed'); - * }; - * - * // add some items to the queue - * q.push({name: 'foo'}, function(err) { - * console.log('finished processing foo'); - * }); - * q.push({name: 'bar'}, function (err) { - * console.log('finished processing bar'); - * }); - * - * // add some items to the queue (batch-wise) - * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) { - * console.log('finished processing item'); - * }); - * - * // add some items to the front of the queue - * q.unshift({name: 'bar'}, function (err) { - * console.log('finished processing bar'); - * }); - */
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/race.js b/node_modules/webpack/node_modules/async/race.js deleted file mode 100644 index 6713c74af..000000000 --- a/node_modules/webpack/node_modules/async/race.js +++ /dev/null @@ -1,70 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = race; - -var _isArray = require('lodash/isArray'); - -var _isArray2 = _interopRequireDefault(_isArray); - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _once = require('./internal/once'); - -var _once2 = _interopRequireDefault(_once); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Runs the `tasks` array of functions in parallel, without waiting until the - * previous function has completed. Once any of the `tasks` complete or pass an - * error to its callback, the main `callback` is immediately called. It's - * equivalent to `Promise.race()`. - * - * @name race - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction} - * to run. Each function can complete with an optional `result` value. - * @param {Function} callback - A callback to run once any of the functions have - * completed. This function gets an error or result from the first function that - * completed. Invoked with (err, result). - * @returns undefined - * @example - * - * async.race([ - * function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * setTimeout(function() { - * callback(null, 'two'); - * }, 100); - * } - * ], - * // main callback - * function(err, result) { - * // the result will be equal to 'two' as it finishes earlier - * }); - */ -function race(tasks, callback) { - callback = (0, _once2.default)(callback || _noop2.default); - if (!(0, _isArray2.default)(tasks)) return callback(new TypeError('First argument to race must be an array of functions')); - if (!tasks.length) return callback(); - for (var i = 0, l = tasks.length; i < l; i++) { - (0, _wrapAsync2.default)(tasks[i])(callback); - } -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/reduce.js b/node_modules/webpack/node_modules/async/reduce.js deleted file mode 100644 index 3fb8019e4..000000000 --- a/node_modules/webpack/node_modules/async/reduce.js +++ /dev/null @@ -1,78 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = reduce; - -var _eachOfSeries = require('./eachOfSeries'); - -var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _once = require('./internal/once'); - -var _once2 = _interopRequireDefault(_once); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Reduces `coll` into a single value using an async `iteratee` to return each - * successive step. `memo` is the initial state of the reduction. This function - * only operates in series. - * - * For performance reasons, it may make sense to split a call to this function - * into a parallel map, and then use the normal `Array.prototype.reduce` on the - * results. This function is for situations where each step in the reduction - * needs to be async; if you can get the data before reducing it, then it's - * probably a good idea to do so. - * - * @name reduce - * @static - * @memberOf module:Collections - * @method - * @alias inject - * @alias foldl - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {*} memo - The initial state of the reduction. - * @param {AsyncFunction} iteratee - A function applied to each item in the - * array to produce the next step in the reduction. - * The `iteratee` should complete with the next state of the reduction. - * If the iteratee complete with an error, the reduction is stopped and the - * main `callback` is immediately called with the error. - * Invoked with (memo, item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result is the reduced value. Invoked with - * (err, result). - * @example - * - * async.reduce([1,2,3], 0, function(memo, item, callback) { - * // pointless async: - * process.nextTick(function() { - * callback(null, memo + item) - * }); - * }, function(err, result) { - * // result is now equal to the last value of memo, which is 6 - * }); - */ -function reduce(coll, memo, iteratee, callback) { - callback = (0, _once2.default)(callback || _noop2.default); - var _iteratee = (0, _wrapAsync2.default)(iteratee); - (0, _eachOfSeries2.default)(coll, function (x, i, callback) { - _iteratee(memo, x, function (err, v) { - memo = v; - callback(err); - }); - }, function (err) { - callback(err, memo); - }); -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/reduceRight.js b/node_modules/webpack/node_modules/async/reduceRight.js deleted file mode 100644 index 3d17d328a..000000000 --- a/node_modules/webpack/node_modules/async/reduceRight.js +++ /dev/null @@ -1,44 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = reduceRight; - -var _reduce = require('./reduce'); - -var _reduce2 = _interopRequireDefault(_reduce); - -var _slice = require('./internal/slice'); - -var _slice2 = _interopRequireDefault(_slice); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. - * - * @name reduceRight - * @static - * @memberOf module:Collections - * @method - * @see [async.reduce]{@link module:Collections.reduce} - * @alias foldr - * @category Collection - * @param {Array} array - A collection to iterate over. - * @param {*} memo - The initial state of the reduction. - * @param {AsyncFunction} iteratee - A function applied to each item in the - * array to produce the next step in the reduction. - * The `iteratee` should complete with the next state of the reduction. - * If the iteratee complete with an error, the reduction is stopped and the - * main `callback` is immediately called with the error. - * Invoked with (memo, item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result is the reduced value. Invoked with - * (err, result). - */ -function reduceRight(array, memo, iteratee, callback) { - var reversed = (0, _slice2.default)(array).reverse(); - (0, _reduce2.default)(reversed, memo, iteratee, callback); -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/reflect.js b/node_modules/webpack/node_modules/async/reflect.js deleted file mode 100644 index 098ba8650..000000000 --- a/node_modules/webpack/node_modules/async/reflect.js +++ /dev/null @@ -1,81 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = reflect; - -var _initialParams = require('./internal/initialParams'); - -var _initialParams2 = _interopRequireDefault(_initialParams); - -var _slice = require('./internal/slice'); - -var _slice2 = _interopRequireDefault(_slice); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Wraps the async function in another function that always completes with a - * result object, even when it errors. - * - * The result object has either the property `error` or `value`. - * - * @name reflect - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} fn - The async function you want to wrap - * @returns {Function} - A function that always passes null to it's callback as - * the error. The second argument to the callback will be an `object` with - * either an `error` or a `value` property. - * @example - * - * async.parallel([ - * async.reflect(function(callback) { - * // do some stuff ... - * callback(null, 'one'); - * }), - * async.reflect(function(callback) { - * // do some more stuff but error ... - * callback('bad stuff happened'); - * }), - * async.reflect(function(callback) { - * // do some more stuff ... - * callback(null, 'two'); - * }) - * ], - * // optional callback - * function(err, results) { - * // values - * // results[0].value = 'one' - * // results[1].error = 'bad stuff happened' - * // results[2].value = 'two' - * }); - */ -function reflect(fn) { - var _fn = (0, _wrapAsync2.default)(fn); - return (0, _initialParams2.default)(function reflectOn(args, reflectCallback) { - args.push(function callback(error, cbArg) { - if (error) { - reflectCallback(null, { error: error }); - } else { - var value; - if (arguments.length <= 2) { - value = cbArg; - } else { - value = (0, _slice2.default)(arguments, 1); - } - reflectCallback(null, { value: value }); - } - }); - - return _fn.apply(this, args); - }); -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/reflectAll.js b/node_modules/webpack/node_modules/async/reflectAll.js deleted file mode 100644 index 966e83de5..000000000 --- a/node_modules/webpack/node_modules/async/reflectAll.js +++ /dev/null @@ -1,105 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = reflectAll; - -var _reflect = require('./reflect'); - -var _reflect2 = _interopRequireDefault(_reflect); - -var _isArray = require('lodash/isArray'); - -var _isArray2 = _interopRequireDefault(_isArray); - -var _arrayMap2 = require('lodash/_arrayMap'); - -var _arrayMap3 = _interopRequireDefault(_arrayMap2); - -var _baseForOwn = require('lodash/_baseForOwn'); - -var _baseForOwn2 = _interopRequireDefault(_baseForOwn); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * A helper function that wraps an array or an object of functions with `reflect`. - * - * @name reflectAll - * @static - * @memberOf module:Utils - * @method - * @see [async.reflect]{@link module:Utils.reflect} - * @category Util - * @param {Array|Object|Iterable} tasks - The collection of - * [async functions]{@link AsyncFunction} to wrap in `async.reflect`. - * @returns {Array} Returns an array of async functions, each wrapped in - * `async.reflect` - * @example - * - * let tasks = [ - * function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * // do some more stuff but error ... - * callback(new Error('bad stuff happened')); - * }, - * function(callback) { - * setTimeout(function() { - * callback(null, 'two'); - * }, 100); - * } - * ]; - * - * async.parallel(async.reflectAll(tasks), - * // optional callback - * function(err, results) { - * // values - * // results[0].value = 'one' - * // results[1].error = Error('bad stuff happened') - * // results[2].value = 'two' - * }); - * - * // an example using an object instead of an array - * let tasks = { - * one: function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * two: function(callback) { - * callback('two'); - * }, - * three: function(callback) { - * setTimeout(function() { - * callback(null, 'three'); - * }, 100); - * } - * }; - * - * async.parallel(async.reflectAll(tasks), - * // optional callback - * function(err, results) { - * // values - * // results.one.value = 'one' - * // results.two.error = 'two' - * // results.three.value = 'three' - * }); - */ -function reflectAll(tasks) { - var results; - if ((0, _isArray2.default)(tasks)) { - results = (0, _arrayMap3.default)(tasks, _reflect2.default); - } else { - results = {}; - (0, _baseForOwn2.default)(tasks, function (task, key) { - results[key] = _reflect2.default.call(this, task); - }); - } - return results; -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/reject.js b/node_modules/webpack/node_modules/async/reject.js deleted file mode 100644 index 53802b531..000000000 --- a/node_modules/webpack/node_modules/async/reject.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _reject = require('./internal/reject'); - -var _reject2 = _interopRequireDefault(_reject); - -var _doParallel = require('./internal/doParallel'); - -var _doParallel2 = _interopRequireDefault(_doParallel); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test. - * - * @name reject - * @static - * @memberOf module:Collections - * @method - * @see [async.filter]{@link module:Collections.filter} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - An async truth test to apply to each item in - * `coll`. - * The should complete with a boolean value as its `result`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - * @example - * - * async.reject(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, results) { - * // results now equals an array of missing files - * createFiles(results); - * }); - */ -exports.default = (0, _doParallel2.default)(_reject2.default); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/rejectLimit.js b/node_modules/webpack/node_modules/async/rejectLimit.js deleted file mode 100644 index 74bba7fba..000000000 --- a/node_modules/webpack/node_modules/async/rejectLimit.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _reject = require('./internal/reject'); - -var _reject2 = _interopRequireDefault(_reject); - -var _doParallelLimit = require('./internal/doParallelLimit'); - -var _doParallelLimit2 = _interopRequireDefault(_doParallelLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a - * time. - * - * @name rejectLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.reject]{@link module:Collections.reject} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {Function} iteratee - An async truth test to apply to each item in - * `coll`. - * The should complete with a boolean value as its `result`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - */ -exports.default = (0, _doParallelLimit2.default)(_reject2.default); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/rejectSeries.js b/node_modules/webpack/node_modules/async/rejectSeries.js deleted file mode 100644 index f905588f4..000000000 --- a/node_modules/webpack/node_modules/async/rejectSeries.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _rejectLimit = require('./rejectLimit'); - -var _rejectLimit2 = _interopRequireDefault(_rejectLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time. - * - * @name rejectSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.reject]{@link module:Collections.reject} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - An async truth test to apply to each item in - * `coll`. - * The should complete with a boolean value as its `result`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - */ -exports.default = (0, _doLimit2.default)(_rejectLimit2.default, 1); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/retry.js b/node_modules/webpack/node_modules/async/retry.js deleted file mode 100644 index 6a1aa1ec8..000000000 --- a/node_modules/webpack/node_modules/async/retry.js +++ /dev/null @@ -1,156 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = retry; - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _constant = require('lodash/constant'); - -var _constant2 = _interopRequireDefault(_constant); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Attempts to get a successful response from `task` no more than `times` times - * before returning an error. If the task is successful, the `callback` will be - * passed the result of the successful task. If all attempts fail, the callback - * will be passed the error and result (if any) of the final attempt. - * - * @name retry - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @see [async.retryable]{@link module:ControlFlow.retryable} - * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an - * object with `times` and `interval` or a number. - * * `times` - The number of attempts to make before giving up. The default - * is `5`. - * * `interval` - The time to wait between retries, in milliseconds. The - * default is `0`. The interval may also be specified as a function of the - * retry count (see example). - * * `errorFilter` - An optional synchronous function that is invoked on - * erroneous result. If it returns `true` the retry attempts will continue; - * if the function returns `false` the retry flow is aborted with the current - * attempt's error and result being returned to the final callback. - * Invoked with (err). - * * If `opts` is a number, the number specifies the number of times to retry, - * with the default interval of `0`. - * @param {AsyncFunction} task - An async function to retry. - * Invoked with (callback). - * @param {Function} [callback] - An optional callback which is called when the - * task has succeeded, or after the final failed attempt. It receives the `err` - * and `result` arguments of the last attempt at completing the `task`. Invoked - * with (err, results). - * - * @example - * - * // The `retry` function can be used as a stand-alone control flow by passing - * // a callback, as shown below: - * - * // try calling apiMethod 3 times - * async.retry(3, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod 3 times, waiting 200 ms between each retry - * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod 10 times with exponential backoff - * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds) - * async.retry({ - * times: 10, - * interval: function(retryCount) { - * return 50 * Math.pow(2, retryCount); - * } - * }, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod the default 5 times no delay between each retry - * async.retry(apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod only when error condition satisfies, all other - * // errors will abort the retry control flow and return to final callback - * async.retry({ - * errorFilter: function(err) { - * return err.message === 'Temporary error'; // only retry on a specific error - * } - * }, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // to retry individual methods that are not as reliable within other - * // control flow functions, use the `retryable` wrapper: - * async.auto({ - * users: api.getUsers.bind(api), - * payments: async.retryable(3, api.getPayments.bind(api)) - * }, function(err, results) { - * // do something with the results - * }); - * - */ -function retry(opts, task, callback) { - var DEFAULT_TIMES = 5; - var DEFAULT_INTERVAL = 0; - - var options = { - times: DEFAULT_TIMES, - intervalFunc: (0, _constant2.default)(DEFAULT_INTERVAL) - }; - - function parseTimes(acc, t) { - if (typeof t === 'object') { - acc.times = +t.times || DEFAULT_TIMES; - - acc.intervalFunc = typeof t.interval === 'function' ? t.interval : (0, _constant2.default)(+t.interval || DEFAULT_INTERVAL); - - acc.errorFilter = t.errorFilter; - } else if (typeof t === 'number' || typeof t === 'string') { - acc.times = +t || DEFAULT_TIMES; - } else { - throw new Error("Invalid arguments for async.retry"); - } - } - - if (arguments.length < 3 && typeof opts === 'function') { - callback = task || _noop2.default; - task = opts; - } else { - parseTimes(options, opts); - callback = callback || _noop2.default; - } - - if (typeof task !== 'function') { - throw new Error("Invalid arguments for async.retry"); - } - - var _task = (0, _wrapAsync2.default)(task); - - var attempt = 1; - function retryAttempt() { - _task(function (err) { - if (err && attempt++ < options.times && (typeof options.errorFilter != 'function' || options.errorFilter(err))) { - setTimeout(retryAttempt, options.intervalFunc(attempt)); - } else { - callback.apply(null, arguments); - } - }); - } - - retryAttempt(); -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/retryable.js b/node_modules/webpack/node_modules/async/retryable.js deleted file mode 100644 index 002bfb0f0..000000000 --- a/node_modules/webpack/node_modules/async/retryable.js +++ /dev/null @@ -1,65 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -exports.default = function (opts, task) { - if (!task) { - task = opts; - opts = null; - } - var _task = (0, _wrapAsync2.default)(task); - return (0, _initialParams2.default)(function (args, callback) { - function taskFn(cb) { - _task.apply(null, args.concat(cb)); - } - - if (opts) (0, _retry2.default)(opts, taskFn, callback);else (0, _retry2.default)(taskFn, callback); - }); -}; - -var _retry = require('./retry'); - -var _retry2 = _interopRequireDefault(_retry); - -var _initialParams = require('./internal/initialParams'); - -var _initialParams2 = _interopRequireDefault(_initialParams); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -module.exports = exports['default']; - -/** - * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method - * wraps a task and makes it retryable, rather than immediately calling it - * with retries. - * - * @name retryable - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.retry]{@link module:ControlFlow.retry} - * @category Control Flow - * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional - * options, exactly the same as from `retry` - * @param {AsyncFunction} task - the asynchronous function to wrap. - * This function will be passed any arguments passed to the returned wrapper. - * Invoked with (...args, callback). - * @returns {AsyncFunction} The wrapped function, which when invoked, will - * retry on an error, based on the parameters specified in `opts`. - * This function will accept the same parameters as `task`. - * @example - * - * async.auto({ - * dep1: async.retryable(3, getFromFlakyService), - * process: ["dep1", async.retryable(3, function (results, cb) { - * maybeProcessData(results.dep1, cb); - * })] - * }, callback); - */
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/select.js b/node_modules/webpack/node_modules/async/select.js deleted file mode 100644 index 54772d562..000000000 --- a/node_modules/webpack/node_modules/async/select.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _filter = require('./internal/filter'); - -var _filter2 = _interopRequireDefault(_filter); - -var _doParallel = require('./internal/doParallel'); - -var _doParallel2 = _interopRequireDefault(_doParallel); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Returns a new array of all the values in `coll` which pass an async truth - * test. This operation is performed in parallel, but the results array will be - * in the same order as the original. - * - * @name filter - * @static - * @memberOf module:Collections - * @method - * @alias select - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - A truth test to apply to each item in `coll`. - * The `iteratee` is passed a `callback(err, truthValue)`, which must be called - * with a boolean argument once it has completed. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - * @example - * - * async.filter(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, results) { - * // results now equals an array of the existing files - * }); - */ -exports.default = (0, _doParallel2.default)(_filter2.default); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/selectLimit.js b/node_modules/webpack/node_modules/async/selectLimit.js deleted file mode 100644 index 06216f785..000000000 --- a/node_modules/webpack/node_modules/async/selectLimit.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _filter = require('./internal/filter'); - -var _filter2 = _interopRequireDefault(_filter); - -var _doParallelLimit = require('./internal/doParallelLimit'); - -var _doParallelLimit2 = _interopRequireDefault(_doParallelLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a - * time. - * - * @name filterLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.filter]{@link module:Collections.filter} - * @alias selectLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {Function} iteratee - A truth test to apply to each item in `coll`. - * The `iteratee` is passed a `callback(err, truthValue)`, which must be called - * with a boolean argument once it has completed. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - */ -exports.default = (0, _doParallelLimit2.default)(_filter2.default); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/selectSeries.js b/node_modules/webpack/node_modules/async/selectSeries.js deleted file mode 100644 index e48d966cb..000000000 --- a/node_modules/webpack/node_modules/async/selectSeries.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _filterLimit = require('./filterLimit'); - -var _filterLimit2 = _interopRequireDefault(_filterLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. - * - * @name filterSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.filter]{@link module:Collections.filter} - * @alias selectSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - A truth test to apply to each item in `coll`. - * The `iteratee` is passed a `callback(err, truthValue)`, which must be called - * with a boolean argument once it has completed. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results) - */ -exports.default = (0, _doLimit2.default)(_filterLimit2.default, 1); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/seq.js b/node_modules/webpack/node_modules/async/seq.js deleted file mode 100644 index ff86ef92d..000000000 --- a/node_modules/webpack/node_modules/async/seq.js +++ /dev/null @@ -1,91 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = seq; - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _slice = require('./internal/slice'); - -var _slice2 = _interopRequireDefault(_slice); - -var _reduce = require('./reduce'); - -var _reduce2 = _interopRequireDefault(_reduce); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -var _arrayMap = require('lodash/_arrayMap'); - -var _arrayMap2 = _interopRequireDefault(_arrayMap); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Version of the compose function that is more natural to read. Each function - * consumes the return value of the previous function. It is the equivalent of - * [compose]{@link module:ControlFlow.compose} with the arguments reversed. - * - * Each function is executed with the `this` binding of the composed function. - * - * @name seq - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.compose]{@link module:ControlFlow.compose} - * @category Control Flow - * @param {...AsyncFunction} functions - the asynchronous functions to compose - * @returns {Function} a function that composes the `functions` in order - * @example - * - * // Requires lodash (or underscore), express3 and dresende's orm2. - * // Part of an app, that fetches cats of the logged user. - * // This example uses `seq` function to avoid overnesting and error - * // handling clutter. - * app.get('/cats', function(request, response) { - * var User = request.models.User; - * async.seq( - * _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data)) - * function(user, fn) { - * user.getCats(fn); // 'getCats' has signature (callback(err, data)) - * } - * )(req.session.user_id, function (err, cats) { - * if (err) { - * console.error(err); - * response.json({ status: 'error', message: err.message }); - * } else { - * response.json({ status: 'ok', message: 'Cats found', data: cats }); - * } - * }); - * }); - */ -function seq() /*...functions*/{ - var _functions = (0, _arrayMap2.default)(arguments, _wrapAsync2.default); - return function () /*...args*/{ - var args = (0, _slice2.default)(arguments); - var that = this; - - var cb = args[args.length - 1]; - if (typeof cb == 'function') { - args.pop(); - } else { - cb = _noop2.default; - } - - (0, _reduce2.default)(_functions, args, function (newargs, fn, cb) { - fn.apply(that, newargs.concat(function (err /*, ...nextargs*/) { - var nextargs = (0, _slice2.default)(arguments, 1); - cb(err, nextargs); - })); - }, function (err, results) { - cb.apply(that, [err].concat(results)); - }); - }; -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/series.js b/node_modules/webpack/node_modules/async/series.js deleted file mode 100644 index e8c292816..000000000 --- a/node_modules/webpack/node_modules/async/series.js +++ /dev/null @@ -1,85 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = series; - -var _parallel = require('./internal/parallel'); - -var _parallel2 = _interopRequireDefault(_parallel); - -var _eachOfSeries = require('./eachOfSeries'); - -var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Run the functions in the `tasks` collection in series, each one running once - * the previous function has completed. If any functions in the series pass an - * error to its callback, no more functions are run, and `callback` is - * immediately called with the value of the error. Otherwise, `callback` - * receives an array of results when `tasks` have completed. - * - * It is also possible to use an object instead of an array. Each property will - * be run as a function, and the results will be passed to the final `callback` - * as an object instead of an array. This can be a more readable way of handling - * results from {@link async.series}. - * - * **Note** that while many implementations preserve the order of object - * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) - * explicitly states that - * - * > The mechanics and order of enumerating the properties is not specified. - * - * So if you rely on the order in which your series of functions are executed, - * and want this to work on all platforms, consider using an array. - * - * @name series - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|Object} tasks - A collection containing - * [async functions]{@link AsyncFunction} to run in series. - * Each function can complete with any number of optional `result` values. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed. This function gets a results array (or object) - * containing all the result arguments passed to the `task` callbacks. Invoked - * with (err, result). - * @example - * async.series([ - * function(callback) { - * // do some stuff ... - * callback(null, 'one'); - * }, - * function(callback) { - * // do some more stuff ... - * callback(null, 'two'); - * } - * ], - * // optional callback - * function(err, results) { - * // results is now equal to ['one', 'two'] - * }); - * - * async.series({ - * one: function(callback) { - * setTimeout(function() { - * callback(null, 1); - * }, 200); - * }, - * two: function(callback){ - * setTimeout(function() { - * callback(null, 2); - * }, 100); - * } - * }, function(err, results) { - * // results is now equal to: {one: 1, two: 2} - * }); - */ -function series(tasks, callback) { - (0, _parallel2.default)(_eachOfSeries2.default, tasks, callback); -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/setImmediate.js b/node_modules/webpack/node_modules/async/setImmediate.js deleted file mode 100644 index e52f7c54b..000000000 --- a/node_modules/webpack/node_modules/async/setImmediate.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _setImmediate = require('./internal/setImmediate'); - -var _setImmediate2 = _interopRequireDefault(_setImmediate); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Calls `callback` on a later loop around the event loop. In Node.js this just - * calls `setImmediate`. In the browser it will use `setImmediate` if - * available, otherwise `setTimeout(callback, 0)`, which means other higher - * priority events may precede the execution of `callback`. - * - * This is used internally for browser-compatibility purposes. - * - * @name setImmediate - * @static - * @memberOf module:Utils - * @method - * @see [async.nextTick]{@link module:Utils.nextTick} - * @category Util - * @param {Function} callback - The function to call on a later loop around - * the event loop. Invoked with (args...). - * @param {...*} args... - any number of additional arguments to pass to the - * callback on the next tick. - * @example - * - * var call_order = []; - * async.nextTick(function() { - * call_order.push('two'); - * // call_order now equals ['one','two'] - * }); - * call_order.push('one'); - * - * async.setImmediate(function (a, b, c) { - * // a, b, and c equal 1, 2, and 3 - * }, 1, 2, 3); - */ -exports.default = _setImmediate2.default; -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/some.js b/node_modules/webpack/node_modules/async/some.js deleted file mode 100644 index a8e70f714..000000000 --- a/node_modules/webpack/node_modules/async/some.js +++ /dev/null @@ -1,52 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createTester = require('./internal/createTester'); - -var _createTester2 = _interopRequireDefault(_createTester); - -var _doParallel = require('./internal/doParallel'); - -var _doParallel2 = _interopRequireDefault(_doParallel); - -var _identity = require('lodash/identity'); - -var _identity2 = _interopRequireDefault(_identity); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Returns `true` if at least one element in the `coll` satisfies an async test. - * If any iteratee call returns `true`, the main `callback` is immediately - * called. - * - * @name some - * @static - * @memberOf module:Collections - * @method - * @alias any - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in parallel. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - * @example - * - * async.some(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // if result is true then at least one of the files exists - * }); - */ -exports.default = (0, _doParallel2.default)((0, _createTester2.default)(Boolean, _identity2.default)); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/someLimit.js b/node_modules/webpack/node_modules/async/someLimit.js deleted file mode 100644 index 24ca3f491..000000000 --- a/node_modules/webpack/node_modules/async/someLimit.js +++ /dev/null @@ -1,43 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createTester = require('./internal/createTester'); - -var _createTester2 = _interopRequireDefault(_createTester); - -var _doParallelLimit = require('./internal/doParallelLimit'); - -var _doParallelLimit2 = _interopRequireDefault(_doParallelLimit); - -var _identity = require('lodash/identity'); - -var _identity2 = _interopRequireDefault(_identity); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. - * - * @name someLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.some]{@link module:Collections.some} - * @alias anyLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in parallel. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - */ -exports.default = (0, _doParallelLimit2.default)((0, _createTester2.default)(Boolean, _identity2.default)); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/someSeries.js b/node_modules/webpack/node_modules/async/someSeries.js deleted file mode 100644 index dc24ed254..000000000 --- a/node_modules/webpack/node_modules/async/someSeries.js +++ /dev/null @@ -1,38 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _someLimit = require('./someLimit'); - -var _someLimit2 = _interopRequireDefault(_someLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. - * - * @name someSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.some]{@link module:Collections.some} - * @alias anySeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in series. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - */ -exports.default = (0, _doLimit2.default)(_someLimit2.default, 1); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/sortBy.js b/node_modules/webpack/node_modules/async/sortBy.js deleted file mode 100644 index ee5e93dc0..000000000 --- a/node_modules/webpack/node_modules/async/sortBy.js +++ /dev/null @@ -1,91 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = sortBy; - -var _arrayMap = require('lodash/_arrayMap'); - -var _arrayMap2 = _interopRequireDefault(_arrayMap); - -var _baseProperty = require('lodash/_baseProperty'); - -var _baseProperty2 = _interopRequireDefault(_baseProperty); - -var _map = require('./map'); - -var _map2 = _interopRequireDefault(_map); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Sorts a list by the results of running each `coll` value through an async - * `iteratee`. - * - * @name sortBy - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a value to use as the sort criteria as - * its `result`. - * Invoked with (item, callback). - * @param {Function} callback - A callback which is called after all the - * `iteratee` functions have finished, or an error occurs. Results is the items - * from the original `coll` sorted by the values returned by the `iteratee` - * calls. Invoked with (err, results). - * @example - * - * async.sortBy(['file1','file2','file3'], function(file, callback) { - * fs.stat(file, function(err, stats) { - * callback(err, stats.mtime); - * }); - * }, function(err, results) { - * // results is now the original array of files sorted by - * // modified date - * }); - * - * // By modifying the callback parameter the - * // sorting order can be influenced: - * - * // ascending order - * async.sortBy([1,9,3,5], function(x, callback) { - * callback(null, x); - * }, function(err,result) { - * // result callback - * }); - * - * // descending order - * async.sortBy([1,9,3,5], function(x, callback) { - * callback(null, x*-1); //<- x*-1 instead of x, turns the order around - * }, function(err,result) { - * // result callback - * }); - */ -function sortBy(coll, iteratee, callback) { - var _iteratee = (0, _wrapAsync2.default)(iteratee); - (0, _map2.default)(coll, function (x, callback) { - _iteratee(x, function (err, criteria) { - if (err) return callback(err); - callback(null, { value: x, criteria: criteria }); - }); - }, function (err, results) { - if (err) return callback(err); - callback(null, (0, _arrayMap2.default)(results.sort(comparator), (0, _baseProperty2.default)('value'))); - }); - - function comparator(left, right) { - var a = left.criteria, - b = right.criteria; - return a < b ? -1 : a > b ? 1 : 0; - } -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/timeout.js b/node_modules/webpack/node_modules/async/timeout.js deleted file mode 100644 index b5cb505eb..000000000 --- a/node_modules/webpack/node_modules/async/timeout.js +++ /dev/null @@ -1,89 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = timeout; - -var _initialParams = require('./internal/initialParams'); - -var _initialParams2 = _interopRequireDefault(_initialParams); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Sets a time limit on an asynchronous function. If the function does not call - * its callback within the specified milliseconds, it will be called with a - * timeout error. The code property for the error object will be `'ETIMEDOUT'`. - * - * @name timeout - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} asyncFn - The async function to limit in time. - * @param {number} milliseconds - The specified time limit. - * @param {*} [info] - Any variable you want attached (`string`, `object`, etc) - * to timeout Error for more information.. - * @returns {AsyncFunction} Returns a wrapped function that can be used with any - * of the control flow functions. - * Invoke this function with the same parameters as you would `asyncFunc`. - * @example - * - * function myFunction(foo, callback) { - * doAsyncTask(foo, function(err, data) { - * // handle errors - * if (err) return callback(err); - * - * // do some stuff ... - * - * // return processed data - * return callback(null, data); - * }); - * } - * - * var wrapped = async.timeout(myFunction, 1000); - * - * // call `wrapped` as you would `myFunction` - * wrapped({ bar: 'bar' }, function(err, data) { - * // if `myFunction` takes < 1000 ms to execute, `err` - * // and `data` will have their expected values - * - * // else `err` will be an Error with the code 'ETIMEDOUT' - * }); - */ -function timeout(asyncFn, milliseconds, info) { - var fn = (0, _wrapAsync2.default)(asyncFn); - - return (0, _initialParams2.default)(function (args, callback) { - var timedOut = false; - var timer; - - function timeoutCallback() { - var name = asyncFn.name || 'anonymous'; - var error = new Error('Callback function "' + name + '" timed out.'); - error.code = 'ETIMEDOUT'; - if (info) { - error.info = info; - } - timedOut = true; - callback(error); - } - - args.push(function () { - if (!timedOut) { - callback.apply(null, arguments); - clearTimeout(timer); - } - }); - - // setup timer and call original function - timer = setTimeout(timeoutCallback, milliseconds); - fn.apply(null, args); - }); -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/times.js b/node_modules/webpack/node_modules/async/times.js deleted file mode 100644 index b5ca24dff..000000000 --- a/node_modules/webpack/node_modules/async/times.js +++ /dev/null @@ -1,50 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _timesLimit = require('./timesLimit'); - -var _timesLimit2 = _interopRequireDefault(_timesLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Calls the `iteratee` function `n` times, and accumulates results in the same - * manner you would use with [map]{@link module:Collections.map}. - * - * @name times - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.map]{@link module:Collections.map} - * @category Control Flow - * @param {number} n - The number of times to run the function. - * @param {AsyncFunction} iteratee - The async function to call `n` times. - * Invoked with the iteration index and a callback: (n, next). - * @param {Function} callback - see {@link module:Collections.map}. - * @example - * - * // Pretend this is some complicated async factory - * var createUser = function(id, callback) { - * callback(null, { - * id: 'user' + id - * }); - * }; - * - * // generate 5 users - * async.times(5, function(n, next) { - * createUser(n, function(err, user) { - * next(err, user); - * }); - * }, function(err, users) { - * // we should now have 5 users - * }); - */ -exports.default = (0, _doLimit2.default)(_timesLimit2.default, Infinity); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/timesLimit.js b/node_modules/webpack/node_modules/async/timesLimit.js deleted file mode 100644 index aad84955c..000000000 --- a/node_modules/webpack/node_modules/async/timesLimit.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = timeLimit; - -var _mapLimit = require('./mapLimit'); - -var _mapLimit2 = _interopRequireDefault(_mapLimit); - -var _baseRange = require('lodash/_baseRange'); - -var _baseRange2 = _interopRequireDefault(_baseRange); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a - * time. - * - * @name timesLimit - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.times]{@link module:ControlFlow.times} - * @category Control Flow - * @param {number} count - The number of times to run the function. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - The async function to call `n` times. - * Invoked with the iteration index and a callback: (n, next). - * @param {Function} callback - see [async.map]{@link module:Collections.map}. - */ -function timeLimit(count, limit, iteratee, callback) { - var _iteratee = (0, _wrapAsync2.default)(iteratee); - (0, _mapLimit2.default)((0, _baseRange2.default)(0, count, 1), limit, _iteratee, callback); -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/timesSeries.js b/node_modules/webpack/node_modules/async/timesSeries.js deleted file mode 100644 index f187a35b2..000000000 --- a/node_modules/webpack/node_modules/async/timesSeries.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _timesLimit = require('./timesLimit'); - -var _timesLimit2 = _interopRequireDefault(_timesLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time. - * - * @name timesSeries - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.times]{@link module:ControlFlow.times} - * @category Control Flow - * @param {number} n - The number of times to run the function. - * @param {AsyncFunction} iteratee - The async function to call `n` times. - * Invoked with the iteration index and a callback: (n, next). - * @param {Function} callback - see {@link module:Collections.map}. - */ -exports.default = (0, _doLimit2.default)(_timesLimit2.default, 1); -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/transform.js b/node_modules/webpack/node_modules/async/transform.js deleted file mode 100644 index 84ee217e8..000000000 --- a/node_modules/webpack/node_modules/async/transform.js +++ /dev/null @@ -1,87 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = transform; - -var _isArray = require('lodash/isArray'); - -var _isArray2 = _interopRequireDefault(_isArray); - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _eachOf = require('./eachOf'); - -var _eachOf2 = _interopRequireDefault(_eachOf); - -var _once = require('./internal/once'); - -var _once2 = _interopRequireDefault(_once); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * A relative of `reduce`. Takes an Object or Array, and iterates over each - * element in series, each step potentially mutating an `accumulator` value. - * The type of the accumulator defaults to the type of collection passed in. - * - * @name transform - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {*} [accumulator] - The initial state of the transform. If omitted, - * it will default to an empty Object or Array, depending on the type of `coll` - * @param {AsyncFunction} iteratee - A function applied to each item in the - * collection that potentially modifies the accumulator. - * Invoked with (accumulator, item, key, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result is the transformed accumulator. - * Invoked with (err, result). - * @example - * - * async.transform([1,2,3], function(acc, item, index, callback) { - * // pointless async: - * process.nextTick(function() { - * acc.push(item * 2) - * callback(null) - * }); - * }, function(err, result) { - * // result is now equal to [2, 4, 6] - * }); - * - * @example - * - * async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) { - * setImmediate(function () { - * obj[key] = val * 2; - * callback(); - * }) - * }, function (err, result) { - * // result is equal to {a: 2, b: 4, c: 6} - * }) - */ -function transform(coll, accumulator, iteratee, callback) { - if (arguments.length <= 3) { - callback = iteratee; - iteratee = accumulator; - accumulator = (0, _isArray2.default)(coll) ? [] : {}; - } - callback = (0, _once2.default)(callback || _noop2.default); - var _iteratee = (0, _wrapAsync2.default)(iteratee); - - (0, _eachOf2.default)(coll, function (v, k, cb) { - _iteratee(accumulator, v, k, cb); - }, function (err) { - callback(err, accumulator); - }); -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/tryEach.js b/node_modules/webpack/node_modules/async/tryEach.js deleted file mode 100644 index f4e4c97d7..000000000 --- a/node_modules/webpack/node_modules/async/tryEach.js +++ /dev/null @@ -1,81 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = tryEach; - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _eachSeries = require('./eachSeries'); - -var _eachSeries2 = _interopRequireDefault(_eachSeries); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -var _slice = require('./internal/slice'); - -var _slice2 = _interopRequireDefault(_slice); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * It runs each task in series but stops whenever any of the functions were - * successful. If one of the tasks were successful, the `callback` will be - * passed the result of the successful task. If all tasks fail, the callback - * will be passed the error and result (if any) of the final attempt. - * - * @name tryEach - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|Object} tasks - A collection containing functions to - * run, each function is passed a `callback(err, result)` it must call on - * completion with an error `err` (which can be `null`) and an optional `result` - * value. - * @param {Function} [callback] - An optional callback which is called when one - * of the tasks has succeeded, or all have failed. It receives the `err` and - * `result` arguments of the last attempt at completing the `task`. Invoked with - * (err, results). - * @example - * async.tryEach([ - * function getDataFromFirstWebsite(callback) { - * // Try getting the data from the first website - * callback(err, data); - * }, - * function getDataFromSecondWebsite(callback) { - * // First website failed, - * // Try getting the data from the backup website - * callback(err, data); - * } - * ], - * // optional callback - * function(err, results) { - * Now do something with the data. - * }); - * - */ -function tryEach(tasks, callback) { - var error = null; - var result; - callback = callback || _noop2.default; - (0, _eachSeries2.default)(tasks, function (task, callback) { - (0, _wrapAsync2.default)(task)(function (err, res /*, ...args*/) { - if (arguments.length > 2) { - result = (0, _slice2.default)(arguments, 1); - } else { - result = res; - } - error = err; - callback(!err); - }); - }, function () { - callback(error, result); - }); -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/unmemoize.js b/node_modules/webpack/node_modules/async/unmemoize.js deleted file mode 100644 index 08f9f9fb3..000000000 --- a/node_modules/webpack/node_modules/async/unmemoize.js +++ /dev/null @@ -1,25 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = unmemoize; -/** - * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, - * unmemoized form. Handy for testing. - * - * @name unmemoize - * @static - * @memberOf module:Utils - * @method - * @see [async.memoize]{@link module:Utils.memoize} - * @category Util - * @param {AsyncFunction} fn - the memoized function - * @returns {AsyncFunction} a function that calls the original unmemoized function - */ -function unmemoize(fn) { - return function () { - return (fn.unmemoized || fn).apply(null, arguments); - }; -} -module.exports = exports["default"];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/until.js b/node_modules/webpack/node_modules/async/until.js deleted file mode 100644 index 29955ab1b..000000000 --- a/node_modules/webpack/node_modules/async/until.js +++ /dev/null @@ -1,41 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = until; - -var _whilst = require('./whilst'); - -var _whilst2 = _interopRequireDefault(_whilst); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when - * stopped, or an error occurs. `callback` will be passed an error and any - * arguments passed to the final `iteratee`'s callback. - * - * The inverse of [whilst]{@link module:ControlFlow.whilst}. - * - * @name until - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.whilst]{@link module:ControlFlow.whilst} - * @category Control Flow - * @param {Function} test - synchronous truth test to perform before each - * execution of `iteratee`. Invoked with (). - * @param {AsyncFunction} iteratee - An async function which is called each time - * `test` fails. Invoked with (callback). - * @param {Function} [callback] - A callback which is called after the test - * function has passed and repeated execution of `iteratee` has stopped. `callback` - * will be passed an error and any arguments passed to the final `iteratee`'s - * callback. Invoked with (err, [results]); - */ -function until(test, iteratee, callback) { - (0, _whilst2.default)(function () { - return !test.apply(this, arguments); - }, iteratee, callback); -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/waterfall.js b/node_modules/webpack/node_modules/async/waterfall.js deleted file mode 100644 index d547d6b1e..000000000 --- a/node_modules/webpack/node_modules/async/waterfall.js +++ /dev/null @@ -1,113 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -exports.default = function (tasks, callback) { - callback = (0, _once2.default)(callback || _noop2.default); - if (!(0, _isArray2.default)(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); - if (!tasks.length) return callback(); - var taskIndex = 0; - - function nextTask(args) { - var task = (0, _wrapAsync2.default)(tasks[taskIndex++]); - args.push((0, _onlyOnce2.default)(next)); - task.apply(null, args); - } - - function next(err /*, ...args*/) { - if (err || taskIndex === tasks.length) { - return callback.apply(null, arguments); - } - nextTask((0, _slice2.default)(arguments, 1)); - } - - nextTask([]); -}; - -var _isArray = require('lodash/isArray'); - -var _isArray2 = _interopRequireDefault(_isArray); - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _once = require('./internal/once'); - -var _once2 = _interopRequireDefault(_once); - -var _slice = require('./internal/slice'); - -var _slice2 = _interopRequireDefault(_slice); - -var _onlyOnce = require('./internal/onlyOnce'); - -var _onlyOnce2 = _interopRequireDefault(_onlyOnce); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -module.exports = exports['default']; - -/** - * Runs the `tasks` array of functions in series, each passing their results to - * the next in the array. However, if any of the `tasks` pass an error to their - * own callback, the next function is not executed, and the main `callback` is - * immediately called with the error. - * - * @name waterfall - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} - * to run. - * Each function should complete with any number of `result` values. - * The `result` values will be passed as arguments, in order, to the next task. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed. This will be passed the results of the last task's - * callback. Invoked with (err, [results]). - * @returns undefined - * @example - * - * async.waterfall([ - * function(callback) { - * callback(null, 'one', 'two'); - * }, - * function(arg1, arg2, callback) { - * // arg1 now equals 'one' and arg2 now equals 'two' - * callback(null, 'three'); - * }, - * function(arg1, callback) { - * // arg1 now equals 'three' - * callback(null, 'done'); - * } - * ], function (err, result) { - * // result now equals 'done' - * }); - * - * // Or, with named functions: - * async.waterfall([ - * myFirstFunction, - * mySecondFunction, - * myLastFunction, - * ], function (err, result) { - * // result now equals 'done' - * }); - * function myFirstFunction(callback) { - * callback(null, 'one', 'two'); - * } - * function mySecondFunction(arg1, arg2, callback) { - * // arg1 now equals 'one' and arg2 now equals 'two' - * callback(null, 'three'); - * } - * function myLastFunction(arg1, callback) { - * // arg1 now equals 'three' - * callback(null, 'done'); - * } - */
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/whilst.js b/node_modules/webpack/node_modules/async/whilst.js deleted file mode 100644 index 9c4d8f6ca..000000000 --- a/node_modules/webpack/node_modules/async/whilst.js +++ /dev/null @@ -1,72 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = whilst; - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _slice = require('./internal/slice'); - -var _slice2 = _interopRequireDefault(_slice); - -var _onlyOnce = require('./internal/onlyOnce'); - -var _onlyOnce2 = _interopRequireDefault(_onlyOnce); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when - * stopped, or an error occurs. - * - * @name whilst - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Function} test - synchronous truth test to perform before each - * execution of `iteratee`. Invoked with (). - * @param {AsyncFunction} iteratee - An async function which is called each time - * `test` passes. Invoked with (callback). - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `iteratee` has stopped. `callback` - * will be passed an error and any arguments passed to the final `iteratee`'s - * callback. Invoked with (err, [results]); - * @returns undefined - * @example - * - * var count = 0; - * async.whilst( - * function() { return count < 5; }, - * function(callback) { - * count++; - * setTimeout(function() { - * callback(null, count); - * }, 1000); - * }, - * function (err, n) { - * // 5 seconds have passed, n = 5 - * } - * ); - */ -function whilst(test, iteratee, callback) { - callback = (0, _onlyOnce2.default)(callback || _noop2.default); - var _iteratee = (0, _wrapAsync2.default)(iteratee); - if (!test()) return callback(null); - var next = function (err /*, ...args*/) { - if (err) return callback(err); - if (test()) return _iteratee(next); - var args = (0, _slice2.default)(arguments, 1); - callback.apply(null, [null].concat(args)); - }; - _iteratee(next); -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/async/wrapSync.js b/node_modules/webpack/node_modules/async/wrapSync.js deleted file mode 100644 index 5e3fc9155..000000000 --- a/node_modules/webpack/node_modules/async/wrapSync.js +++ /dev/null @@ -1,110 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = asyncify; - -var _isObject = require('lodash/isObject'); - -var _isObject2 = _interopRequireDefault(_isObject); - -var _initialParams = require('./internal/initialParams'); - -var _initialParams2 = _interopRequireDefault(_initialParams); - -var _setImmediate = require('./internal/setImmediate'); - -var _setImmediate2 = _interopRequireDefault(_setImmediate); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Take a sync function and make it async, passing its return value to a - * callback. This is useful for plugging sync functions into a waterfall, - * series, or other async functions. Any arguments passed to the generated - * function will be passed to the wrapped function (except for the final - * callback argument). Errors thrown will be passed to the callback. - * - * If the function passed to `asyncify` returns a Promise, that promises's - * resolved/rejected state will be used to call the callback, rather than simply - * the synchronous return value. - * - * This also means you can asyncify ES2017 `async` functions. - * - * @name asyncify - * @static - * @memberOf module:Utils - * @method - * @alias wrapSync - * @category Util - * @param {Function} func - The synchronous function, or Promise-returning - * function to convert to an {@link AsyncFunction}. - * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be - * invoked with `(args..., callback)`. - * @example - * - * // passing a regular synchronous function - * async.waterfall([ - * async.apply(fs.readFile, filename, "utf8"), - * async.asyncify(JSON.parse), - * function (data, next) { - * // data is the result of parsing the text. - * // If there was a parsing error, it would have been caught. - * } - * ], callback); - * - * // passing a function returning a promise - * async.waterfall([ - * async.apply(fs.readFile, filename, "utf8"), - * async.asyncify(function (contents) { - * return db.model.create(contents); - * }), - * function (model, next) { - * // `model` is the instantiated model object. - * // If there was an error, this function would be skipped. - * } - * ], callback); - * - * // es2017 example, though `asyncify` is not needed if your JS environment - * // supports async functions out of the box - * var q = async.queue(async.asyncify(async function(file) { - * var intermediateStep = await processFile(file); - * return await somePromise(intermediateStep) - * })); - * - * q.push(files); - */ -function asyncify(func) { - return (0, _initialParams2.default)(function (args, callback) { - var result; - try { - result = func.apply(this, args); - } catch (e) { - return callback(e); - } - // if result is Promise object - if ((0, _isObject2.default)(result) && typeof result.then === 'function') { - result.then(function (value) { - invokeCallback(callback, null, value); - }, function (err) { - invokeCallback(callback, err.message ? err : new Error(err)); - }); - } else { - callback(null, result); - } - }); -} - -function invokeCallback(callback, error, value) { - try { - callback(error, value); - } catch (e) { - (0, _setImmediate2.default)(rethrow, e); - } -} - -function rethrow(error) { - throw error; -} -module.exports = exports['default'];
\ No newline at end of file diff --git a/node_modules/webpack/node_modules/enhanced-resolve/README.md b/node_modules/webpack/node_modules/enhanced-resolve/README.md deleted file mode 100644 index 95ad6d4ce..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/README.md +++ /dev/null @@ -1,118 +0,0 @@ -# enhanced-resolve
-
-Offers an async require.resolve function. It's highly configurable.
-
-## Features
-
-* plugin system
-* provide a custom filesystem
-* sync and async node.js filesystems included
-
-
-## Getting Started
-### Install
-```sh
-# npm
-npm install enhanced-resolve
-# or Yarn
-yarn add enhanced-resolve
-```
-
-### Creating a Resolver
-The easiest way to create a resolver is to use the `createResolver` function on `ResolveFactory`, along with one of the supplied File System implementations.
-```js
-const {
- NodeJsInputFileSystem,
- CachedInputFileSystem,
- ResolverFactory
-} = require('enhanced-resolve');
-
-// create a resolver
-const myResolver = ResolverFactory.createResolver({
- // Typical usage will consume the `NodeJsInputFileSystem` + `CachedInputFileSystem`, which wraps the Node.js `fs` wrapper to add resilience + caching.
- fileSystem: new CachedInputFileSystem(new NodeJsInputFileSystem(), 4000),
- extensions: ['.js', '.json']
- /* any other resolver options here. Options/defaults can be seen below */
-});
-
-// resolve a file with the new resolver
-const context = {};
-const lookupStartPath = '/Users/webpack/some/root/dir';
-const request = './path/to-look-up.js';
-myResolver.resolve({}, lookupStartPath, request, (err/*Error*/, filepath/*string*/) => {
- // Do something with the path
-});
-```
-
-For more examples creating different types resolvers (sync/async, context, etc) see `lib/node.js`.
-#### Resolver Options
-| Field | Default | Description |
-| ------------------------ | --------------------------- | ---------------------------------------------------------------------------------- |
-| modules | ["node_modules"] | A list of directories to resolve modules from, can be absolute path or folder name |
-| descriptionFiles | ["package.json"] | A list of description files to read from |
-| plugins | [] | A list of additional resolve plugins which should be applied |
-| mainFields | ["main"] | A list of main fields in description files |
-| aliasFields | [] | A list of alias fields in description files |
-| mainFiles | ["index"] | A list of main files in directories |
-| extensions | [".js", ".json", ".node"] | A list of extensions which should be tried for files |
-| enforceExtension | false | Enforce that a extension from extensions must be used |
-| moduleExtensions | [] | A list of module extensions which should be tried for modules |
-| enforceModuleExtension | false | Enforce that a extension from moduleExtensions must be used |
-| alias | [] | A list of module alias configurations or an object which maps key to value |
-| resolveToContext | false | Resolve to a context instead of a file |
-| unsafeCache | false | Use this cache object to unsafely cache the successful requests |
-| cacheWithContext | true | If unsafe cache is enabled, includes `request.context` in the cache key |
-| cachePredicate | function() { return true }; | A function which decides whether a request should be cached or not. An object is passed to the function with `path` and `request` properties. |
-| fileSystem | | The file system which should be used |
-| resolver | undefined | A prepared Resolver to which the plugins are attached |
-
-## Plugins
-Similar to `webpack`, the core of `enhanced-resolve` functionality is implemented as individual plugins that are executed using [`Tapable`](https://github.com/webpack/tapable). These plugins can extend the functionality of the library, adding other ways for files/contexts to be resolved.
-
-A plugin should be a `class` (or its ES5 equivalent) with an `apply` method. The `apply` method will receive a `resolver` instance, that can be used to hook in to the event system.
-
-### Plugin Boilerplate
-```js
-class MyResolverPlugin {
- constructor(source, target) {
- this.source = source;
- this.target = target;
- }
-
- apply(resolver) {
- resolver.plugin(this.source, (request, callback) => {
- // Any logic you need to create a new `request` can go here
- resolver.doResolve(this.target, request, null, callback);
- });
- }
-}
-```
-
-Plugins are executed in a pipeline, and register which event they should be executed before/after. In the example above, `source` is the name of the event that starts the pipeline, and `target` is what event this plugin should fire, which is what continues the execution of the pipeline. For an example of how these different plugin events create a chain, see `lib/ResolverFactory.js`, in the `//// pipeline ////` section.
-
-## Tests
-
-``` javascript
-npm test
-```
-
-[](http://travis-ci.org/webpack/enhanced-resolve)
-
-
-## Passing options from webpack
-If you are using `webpack`, and you want to pass custom options to `enhanced-resolve`, the options are passed from the `resolve` key of your webpack configuration e.g.:
-
-```
-resolve: {
- extensions: ['', '.js', '.jsx'],
- modules: ['src', 'node_modules'],
- plugins: [new DirectoryNamedWebpackPlugin()]
- ...
-},
-```
-
-## License
-
-Copyright (c) 2012-2016 Tobias Koppers
-
-MIT (http://www.opensource.org/licenses/mit-license.php)
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/AliasFieldPlugin.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/AliasFieldPlugin.js deleted file mode 100644 index 70b6b97d6..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/AliasFieldPlugin.js +++ /dev/null @@ -1,51 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-
-var DescriptionFileUtils = require("./DescriptionFileUtils");
-var createInnerCallback = require("./createInnerCallback");
-var getInnerRequest = require("./getInnerRequest");
-
-function AliasFieldPlugin(source, field, target) {
- this.source = source;
- this.field = field;
- this.target = target;
-}
-module.exports = AliasFieldPlugin;
-
-AliasFieldPlugin.prototype.apply = function(resolver) {
- var target = this.target;
- var field = this.field;
- resolver.plugin(this.source, function(request, callback) {
- if(!request.descriptionFileData) return callback();
- var innerRequest = getInnerRequest(resolver, request);
- if(!innerRequest) return callback();
- var fieldData = DescriptionFileUtils.getField(request.descriptionFileData, field);
- if(typeof fieldData !== "object") {
- if(callback.log) callback.log("Field '" + field + "' doesn't contain a valid alias configuration");
- return callback();
- }
- var data1 = fieldData[innerRequest];
- var data2 = fieldData[innerRequest.replace(/^\.\//, "")];
- var data = typeof data1 !== "undefined" ? data1 : data2;
- if(data === innerRequest) return callback();
- if(data === undefined) return callback();
- if(data === false) {
- var ignoreObj = Object.assign({}, request, {
- path: false
- });
- return callback(null, ignoreObj);
- }
- var obj = Object.assign({}, request, {
- path: request.descriptionFileRoot,
- request: data
- });
- resolver.doResolve(target, obj, "aliased from description file " + request.descriptionFilePath + " with mapping '" + innerRequest + "' to '" + data + "'", createInnerCallback(function(err, result) {
- if(arguments.length > 0) return callback(err, result);
-
- // Don't allow other aliasing or raw request
- callback(null, null);
- }, callback));
- });
-};
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/AliasPlugin.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/AliasPlugin.js deleted file mode 100644 index 86f2a6fba..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/AliasPlugin.js +++ /dev/null @@ -1,57 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-var createInnerCallback = require("./createInnerCallback");
-
-function startsWith(string, searchString) {
- var stringLength = string.length;
- var searchLength = searchString.length;
-
- // early out if the search length is greater than the search string
- if(searchLength > stringLength) {
- return false;
- }
- var index = -1;
- while(++index < searchLength) {
- if(string.charCodeAt(index) !== searchString.charCodeAt(index)) {
- return false;
- }
- }
- return true;
-}
-
-function AliasPlugin(source, options, target) {
- this.source = source;
- this.name = options.name;
- this.alias = options.alias;
- this.onlyModule = options.onlyModule;
- this.target = target;
-}
-module.exports = AliasPlugin;
-
-AliasPlugin.prototype.apply = function(resolver) {
- var target = this.target;
- var name = this.name;
- var alias = this.alias;
- var onlyModule = this.onlyModule;
- resolver.plugin(this.source, function(request, callback) {
- var innerRequest = request.request;
- if(!innerRequest) return callback();
- if(innerRequest === name || (!onlyModule && startsWith(innerRequest, name + "/"))) {
- if(innerRequest !== alias && !startsWith(innerRequest, alias + "/")) {
- var newRequestStr = alias + innerRequest.substr(name.length);
- var obj = Object.assign({}, request, {
- request: newRequestStr
- });
- return resolver.doResolve(target, obj, "aliased with mapping '" + name + "': '" + alias + "' to '" + newRequestStr + "'", createInnerCallback(function(err, result) {
- if(arguments.length > 0) return callback(err, result);
-
- // don't allow other aliasing or raw request
- callback(null, null);
- }, callback));
- }
- }
- return callback();
- });
-};
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/AppendPlugin.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/AppendPlugin.js deleted file mode 100644 index a42ff3679..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/AppendPlugin.js +++ /dev/null @@ -1,22 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-function AppendPlugin(source, appending, target) {
- this.source = source;
- this.appending = appending;
- this.target = target;
-}
-module.exports = AppendPlugin;
-
-AppendPlugin.prototype.apply = function(resolver) {
- var target = this.target;
- var appending = this.appending;
- resolver.plugin(this.source, function(request, callback) {
- var obj = Object.assign({}, request, {
- path: request.path + appending,
- relativePath: request.relativePath && (request.relativePath + appending)
- });
- resolver.doResolve(target, obj, appending, callback);
- });
-};
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js deleted file mode 100644 index 69e75d2c3..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js +++ /dev/null @@ -1,271 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-function Storage(duration) {
- this.duration = duration;
- this.running = new Map();
- this.data = new Map();
- this.levels = [];
- if(duration > 0) {
- this.levels.push(new Set(), new Set(), new Set(), new Set(), new Set(), new Set(), new Set(), new Set(), new Set());
- for(var i = 8000; i < duration; i += 500)
- this.levels.push(new Set());
- }
- this.count = 0;
- this.interval = null;
- this.needTickCheck = false;
- this.nextTick = null;
- this.passive = true;
- this.tick = this.tick.bind(this);
-}
-
-Storage.prototype.ensureTick = function() {
- if(!this.interval && this.duration > 0 && !this.nextTick)
- this.interval = setInterval(this.tick, Math.floor(this.duration / this.levels.length));
-};
-
-Storage.prototype.finished = function(name, err, result) {
- var callbacks = this.running.get(name);
- this.running.delete(name);
- if(this.duration > 0) {
- this.data.set(name, [err, result]);
- var levelData = this.levels[0];
- this.count -= levelData.size;
- levelData.add(name);
- this.count += levelData.size;
- this.ensureTick();
- }
- for(var i = 0; i < callbacks.length; i++) {
- callbacks[i](err, result);
- }
-};
-
-Storage.prototype.finishedSync = function(name, err, result) {
- if(this.duration > 0) {
- this.data.set(name, [err, result]);
- var levelData = this.levels[0];
- this.count -= levelData.size;
- levelData.add(name);
- this.count += levelData.size;
- this.ensureTick();
- }
-};
-
-Storage.prototype.provide = function(name, provider, callback) {
- if(typeof name !== "string") {
- callback(new TypeError("path must be a string"));
- return;
- }
- var running = this.running.get(name);
- if(running) {
- running.push(callback);
- return;
- }
- if(this.duration > 0) {
- this.checkTicks();
- var data = this.data.get(name);
- if(data) {
- return process.nextTick(function() {
- callback.apply(null, data);
- });
- }
- }
- this.running.set(name, running = [callback]);
- var _this = this;
- provider(name, function(err, result) {
- _this.finished(name, err, result);
- });
-};
-
-Storage.prototype.provideSync = function(name, provider) {
- if(typeof name !== "string") {
- throw new TypeError("path must be a string");
- }
- if(this.duration > 0) {
- this.checkTicks();
- var data = this.data.get(name);
- if(data) {
- if(data[0])
- throw data[0];
- return data[1];
- }
- }
- try {
- var result = provider(name);
- } catch(e) {
- this.finishedSync(name, e);
- throw e;
- }
- this.finishedSync(name, null, result);
- return result;
-};
-
-Storage.prototype.tick = function() {
- var decay = this.levels.pop();
- for(var item of decay) {
- this.data.delete(item);
- }
- this.count -= decay.size;
- decay.clear();
- this.levels.unshift(decay);
- if(this.count === 0) {
- clearInterval(this.interval);
- this.interval = null;
- this.nextTick = null;
- return true;
- } else if(this.nextTick) {
- this.nextTick += Math.floor(this.duration / this.levels.length);
- var time = new Date().getTime();
- if(this.nextTick > time) {
- this.nextTick = null;
- this.interval = setInterval(this.tick, Math.floor(this.duration / this.levels.length));
- return true;
- }
- } else if(this.passive) {
- clearInterval(this.interval);
- this.interval = null;
- this.nextTick = new Date().getTime() + Math.floor(this.duration / this.levels.length);
- } else {
- this.passive = true;
- }
-};
-
-Storage.prototype.checkTicks = function() {
- this.passive = false;
- if(this.nextTick) {
- while(!this.tick());
- }
-};
-
-Storage.prototype.purge = function(what) {
- if(!what) {
- this.count = 0;
- clearInterval(this.interval);
- this.nextTick = null;
- this.data.clear();
- this.levels.forEach(function(level) {
- level.clear();
- });
- } else if(typeof what === "string") {
- for(var key of this.data.keys()) {
- if(key.startsWith(what))
- this.data.delete(key);
- }
- } else {
- for(var i = what.length - 1; i >= 0; i--) {
- this.purge(what[i]);
- }
- }
-};
-
-function CachedInputFileSystem(fileSystem, duration) {
- this.fileSystem = fileSystem;
- this._statStorage = new Storage(duration);
- this._readdirStorage = new Storage(duration);
- this._readFileStorage = new Storage(duration);
- this._readJsonStorage = new Storage(duration);
- this._readlinkStorage = new Storage(duration);
-
- this._stat = this.fileSystem.stat ? this.fileSystem.stat.bind(this.fileSystem) : null;
- if(!this._stat) this.stat = null;
-
- this._statSync = this.fileSystem.statSync ? this.fileSystem.statSync.bind(this.fileSystem) : null;
- if(!this._statSync) this.statSync = null;
-
- this._readdir = this.fileSystem.readdir ? this.fileSystem.readdir.bind(this.fileSystem) : null;
- if(!this._readdir) this.readdir = null;
-
- this._readdirSync = this.fileSystem.readdirSync ? this.fileSystem.readdirSync.bind(this.fileSystem) : null;
- if(!this._readdirSync) this.readdirSync = null;
-
- this._readFile = this.fileSystem.readFile ? this.fileSystem.readFile.bind(this.fileSystem) : null;
- if(!this._readFile) this.readFile = null;
-
- this._readFileSync = this.fileSystem.readFileSync ? this.fileSystem.readFileSync.bind(this.fileSystem) : null;
- if(!this._readFileSync) this.readFileSync = null;
-
- if(this.fileSystem.readJson) {
- this._readJson = this.fileSystem.readJson.bind(this.fileSystem);
- } else if(this.readFile) {
- this._readJson = function(path, callback) {
- this.readFile(path, function(err, buffer) {
- if(err) return callback(err);
- try {
- var data = JSON.parse(buffer.toString("utf-8"));
- } catch(e) {
- return callback(e);
- }
- callback(null, data);
- });
- }.bind(this);
- } else {
- this.readJson = null;
- }
- if(this.fileSystem.readJsonSync) {
- this._readJsonSync = this.fileSystem.readJsonSync.bind(this.fileSystem);
- } else if(this.readFileSync) {
- this._readJsonSync = function(path) {
- var buffer = this.readFileSync(path);
- var data = JSON.parse(buffer.toString("utf-8"));
- return data;
- }.bind(this);
- } else {
- this.readJsonSync = null;
- }
-
- this._readlink = this.fileSystem.readlink ? this.fileSystem.readlink.bind(this.fileSystem) : null;
- if(!this._readlink) this.readlink = null;
-
- this._readlinkSync = this.fileSystem.readlinkSync ? this.fileSystem.readlinkSync.bind(this.fileSystem) : null;
- if(!this._readlinkSync) this.readlinkSync = null;
-}
-module.exports = CachedInputFileSystem;
-
-CachedInputFileSystem.prototype.stat = function(path, callback) {
- this._statStorage.provide(path, this._stat, callback);
-};
-
-CachedInputFileSystem.prototype.readdir = function(path, callback) {
- this._readdirStorage.provide(path, this._readdir, callback);
-};
-
-CachedInputFileSystem.prototype.readFile = function(path, callback) {
- this._readFileStorage.provide(path, this._readFile, callback);
-};
-
-CachedInputFileSystem.prototype.readJson = function(path, callback) {
- this._readJsonStorage.provide(path, this._readJson, callback);
-};
-
-CachedInputFileSystem.prototype.readlink = function(path, callback) {
- this._readlinkStorage.provide(path, this._readlink, callback);
-};
-
-CachedInputFileSystem.prototype.statSync = function(path) {
- return this._statStorage.provideSync(path, this._statSync);
-};
-
-CachedInputFileSystem.prototype.readdirSync = function(path) {
- return this._readdirStorage.provideSync(path, this._readdirSync);
-};
-
-CachedInputFileSystem.prototype.readFileSync = function(path) {
- return this._readFileStorage.provideSync(path, this._readFileSync);
-};
-
-CachedInputFileSystem.prototype.readJsonSync = function(path) {
- return this._readJsonStorage.provideSync(path, this._readJsonSync);
-};
-
-CachedInputFileSystem.prototype.readlinkSync = function(path) {
- return this._readlinkStorage.provideSync(path, this._readlinkSync);
-};
-
-CachedInputFileSystem.prototype.purge = function(what) {
- this._statStorage.purge(what);
- this._readdirStorage.purge(what);
- this._readFileStorage.purge(what);
- this._readlinkStorage.purge(what);
- this._readJsonStorage.purge(what);
-};
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/CloneBasenamePlugin.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/CloneBasenamePlugin.js deleted file mode 100644 index d6ad4bc06..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/CloneBasenamePlugin.js +++ /dev/null @@ -1,24 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-var basename = require("./getPaths").basename;
-
-function CloneBasenamePlugin(source, target) {
- this.source = source;
- this.target = target;
-}
-module.exports = CloneBasenamePlugin;
-
-CloneBasenamePlugin.prototype.apply = function(resolver) {
- var target = this.target;
- resolver.plugin(this.source, function(request, callback) {
- var filename = basename(request.path);
- var filePath = resolver.join(request.path, filename);
- var obj = Object.assign({}, request, {
- path: filePath,
- relativePath: request.relativePath && resolver.join(request.relativePath, filename)
- });
- resolver.doResolve(target, obj, "using path: " + filePath, callback);
- });
-};
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/ConcordExtensionsPlugin.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/ConcordExtensionsPlugin.js deleted file mode 100644 index 2a3c41a94..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/ConcordExtensionsPlugin.js +++ /dev/null @@ -1,37 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-var concord = require("./concord");
-var DescriptionFileUtils = require("./DescriptionFileUtils");
-var forEachBail = require("./forEachBail");
-var createInnerCallback = require("./createInnerCallback");
-
-function ConcordExtensionsPlugin(source, options, target) {
- this.source = source;
- this.options = options;
- this.target = target;
-}
-module.exports = ConcordExtensionsPlugin;
-
-ConcordExtensionsPlugin.prototype.apply = function(resolver) {
- var target = this.target;
- resolver.plugin(this.source, function(request, callback) {
- var concordField = DescriptionFileUtils.getField(request.descriptionFileData, "concord");
- if(!concordField) return callback();
- var extensions = concord.getExtensions(request.context, concordField);
- if(!extensions) return callback();
- var topLevelCallback = callback;
- forEachBail(extensions, function(appending, callback) {
- var obj = Object.assign({}, request, {
- path: request.path + appending,
- relativePath: request.relativePath && (request.relativePath + appending)
- });
- resolver.doResolve(target, obj, "concord extension: " + appending, createInnerCallback(callback, topLevelCallback));
- }, function(err, result) {
- if(arguments.length > 0) return callback(err, result);
-
- callback(null, null);
- });
- });
-};
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/ConcordMainPlugin.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/ConcordMainPlugin.js deleted file mode 100644 index b3b672d8a..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/ConcordMainPlugin.js +++ /dev/null @@ -1,30 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-var path = require("path");
-var concord = require("./concord");
-var DescriptionFileUtils = require("./DescriptionFileUtils");
-
-function ConcordMainPlugin(source, options, target) {
- this.source = source;
- this.options = options;
- this.target = target;
-}
-module.exports = ConcordMainPlugin;
-
-ConcordMainPlugin.prototype.apply = function(resolver) {
- var target = this.target;
- resolver.plugin(this.source, function(request, callback) {
- if(request.path !== request.descriptionFileRoot) return callback();
- var concordField = DescriptionFileUtils.getField(request.descriptionFileData, "concord");
- if(!concordField) return callback();
- var mainModule = concord.getMain(request.context, concordField);
- if(!mainModule) return callback();
- var obj = Object.assign({}, request, {
- request: mainModule
- });
- var filename = path.basename(request.descriptionFilePath);
- return resolver.doResolve(target, obj, "use " + mainModule + " from " + filename, callback);
- });
-};
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/ConcordModulesPlugin.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/ConcordModulesPlugin.js deleted file mode 100644 index 2aa35ab87..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/ConcordModulesPlugin.js +++ /dev/null @@ -1,44 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-var concord = require("./concord");
-var DescriptionFileUtils = require("./DescriptionFileUtils");
-var createInnerCallback = require("./createInnerCallback");
-var getInnerRequest = require("./getInnerRequest");
-
-function ConcordModulesPlugin(source, options, target) {
- this.source = source;
- this.options = options;
- this.target = target;
-}
-module.exports = ConcordModulesPlugin;
-
-ConcordModulesPlugin.prototype.apply = function(resolver) {
- var target = this.target;
- resolver.plugin(this.source, function(request, callback) {
- var innerRequest = getInnerRequest(resolver, request);
- if(!innerRequest) return callback();
- var concordField = DescriptionFileUtils.getField(request.descriptionFileData, "concord");
- if(!concordField) return callback();
- var data = concord.matchModule(request.context, concordField, innerRequest);
- if(data === innerRequest) return callback();
- if(data === undefined) return callback();
- if(data === false) {
- var ignoreObj = Object.assign({}, request, {
- path: false
- });
- return callback(null, ignoreObj);
- }
- var obj = Object.assign({}, request, {
- path: request.descriptionFileRoot,
- request: data
- });
- resolver.doResolve(target, obj, "aliased from description file " + request.descriptionFilePath + " with mapping '" + innerRequest + "' to '" + data + "'", createInnerCallback(function(err, result) {
- if(arguments.length > 0) return callback(err, result);
-
- // Don't allow other aliasing or raw request
- callback(null, null);
- }, callback));
- });
-};
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/DescriptionFilePlugin.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/DescriptionFilePlugin.js deleted file mode 100644 index ad4a9a3c6..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/DescriptionFilePlugin.js +++ /dev/null @@ -1,51 +0,0 @@ -"use strict";
-/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-const createInnerCallback = require("./createInnerCallback");
-const DescriptionFileUtils = require("./DescriptionFileUtils");
-
-class DescriptionFilePlugin {
- constructor(source, filenames, target) {
- this.source = source;
- this.filenames = [].concat(filenames);
- this.target = target;
- }
-
- apply(resolver) {
- const filenames = this.filenames;
- const target = this.target;
- resolver.plugin(this.source, (request, callback) => {
- const directory = request.path;
- DescriptionFileUtils.loadDescriptionFile(resolver, directory, filenames, ((err, result) => {
- if(err) return callback(err);
- if(!result) {
- if(callback.missing) {
- filenames.forEach((filename) => {
- callback.missing.push(resolver.join(directory, filename));
- });
- }
- if(callback.log) callback.log("No description file found");
- return callback();
- }
- const relativePath = "." + request.path.substr(result.directory.length).replace(/\\/g, "/");
- const obj = Object.assign({}, request, {
- descriptionFilePath: result.path,
- descriptionFileData: result.content,
- descriptionFileRoot: result.directory,
- relativePath: relativePath
- });
- resolver.doResolve(target, obj, "using description file: " + result.path + " (relative path: " + relativePath + ")", createInnerCallback((err, result) => {
- if(err) return callback(err);
- if(result) return callback(null, result);
-
- // Don't allow other description files or none at all
- callback(null, null);
- }, callback));
- }));
- });
- }
-}
-
-module.exports = DescriptionFilePlugin;
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/DescriptionFileUtils.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/DescriptionFileUtils.js deleted file mode 100644 index 084d29ec9..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/DescriptionFileUtils.js +++ /dev/null @@ -1,93 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-var forEachBail = require("./forEachBail");
-
-function loadDescriptionFile(resolver, directory, filenames, callback) {
- (function findDescriptionFile() {
- forEachBail(filenames, function(filename, callback) {
- var descriptionFilePath = resolver.join(directory, filename);
- if(resolver.fileSystem.readJson) {
- resolver.fileSystem.readJson(descriptionFilePath, function(err, content) {
- if(err) {
- if(typeof err.code !== "undefined") return callback();
- return onJson(err);
- }
- onJson(null, content);
- });
- } else {
- resolver.fileSystem.readFile(descriptionFilePath, function(err, content) {
- if(err) return callback();
- try {
- var json = JSON.parse(content);
- } catch(e) {
- onJson(e);
- }
- onJson(null, json);
- });
- }
-
- function onJson(err, content) {
- if(err) {
- if(callback.log)
- callback.log(descriptionFilePath + " (directory description file): " + err);
- else
- err.message = descriptionFilePath + " (directory description file): " + err;
- return callback(err);
- }
- callback(null, {
- content: content,
- directory: directory,
- path: descriptionFilePath
- });
- }
- }, function(err, result) {
- if(err) return callback(err);
- if(result) {
- return callback(null, result);
- } else {
- directory = cdUp(directory);
- if(!directory) {
- return callback();
- } else {
- return findDescriptionFile();
- }
- }
- });
- }());
-}
-
-function getField(content, field) {
- if(!content) return undefined;
- if(Array.isArray(field)) {
- var current = content;
- for(var j = 0; j < field.length; j++) {
- if(current === null || typeof current !== "object") {
- current = null;
- break;
- }
- current = current[field[j]];
- }
- if(typeof current === "object") {
- return current;
- }
- } else {
- if(typeof content[field] === "object") {
- return content[field];
- }
- }
-}
-
-function cdUp(directory) {
- if(directory === "/") return null;
- var i = directory.lastIndexOf("/"),
- j = directory.lastIndexOf("\\");
- var p = i < 0 ? j : j < 0 ? i : i < j ? j : i;
- if(p < 0) return null;
- return directory.substr(0, p || 1);
-}
-
-exports.loadDescriptionFile = loadDescriptionFile;
-exports.getField = getField;
-exports.cdUp = cdUp;
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/DirectoryExistsPlugin.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/DirectoryExistsPlugin.js deleted file mode 100644 index 7e88d68d0..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/DirectoryExistsPlugin.js +++ /dev/null @@ -1,30 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-function DirectoryExistsPlugin(source, target) {
- this.source = source;
- this.target = target;
-}
-module.exports = DirectoryExistsPlugin;
-
-DirectoryExistsPlugin.prototype.apply = function(resolver) {
- var target = this.target;
- resolver.plugin(this.source, function(request, callback) {
- var fs = this.fileSystem;
- var directory = request.path;
- fs.stat(directory, function(err, stat) {
- if(err || !stat) {
- if(callback.missing) callback.missing.push(directory);
- if(callback.log) callback.log(directory + " doesn't exist");
- return callback();
- }
- if(!stat.isDirectory()) {
- if(callback.missing) callback.missing.push(directory);
- if(callback.log) callback.log(directory + " is not a directory");
- return callback();
- }
- this.doResolve(target, request, "existing directory", callback);
- }.bind(this));
- });
-};
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/FileExistsPlugin.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/FileExistsPlugin.js deleted file mode 100644 index 59fc6a5f1..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/FileExistsPlugin.js +++ /dev/null @@ -1,30 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-function FileExistsPlugin(source, target) {
- this.source = source;
- this.target = target;
-}
-module.exports = FileExistsPlugin;
-
-FileExistsPlugin.prototype.apply = function(resolver) {
- var target = this.target;
- resolver.plugin(this.source, function(request, callback) {
- var fs = this.fileSystem;
- var file = request.path;
- fs.stat(file, function(err, stat) {
- if(err || !stat) {
- if(callback.missing) callback.missing.push(file);
- if(callback.log) callback.log(file + " doesn't exist");
- return callback();
- }
- if(!stat.isFile()) {
- if(callback.missing) callback.missing.push(file);
- if(callback.log) callback.log(file + " is not a file");
- return callback();
- }
- this.doResolve(target, request, "existing file: " + file, callback, true);
- }.bind(this));
- });
-};
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/FileKindPlugin.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/FileKindPlugin.js deleted file mode 100644 index d42bc22f3..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/FileKindPlugin.js +++ /dev/null @@ -1,19 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-function FileKindPlugin(source, target) {
- this.source = source;
- this.target = target;
-}
-module.exports = FileKindPlugin;
-
-FileKindPlugin.prototype.apply = function(resolver) {
- var target = this.target;
- resolver.plugin(this.source, function(request, callback) {
- if(request.directory) return callback();
- var obj = Object.assign({}, request);
- delete obj.directory;
- resolver.doResolve(target, obj, null, callback);
- });
-};
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/JoinRequestPlugin.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/JoinRequestPlugin.js deleted file mode 100644 index ac828eb31..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/JoinRequestPlugin.js +++ /dev/null @@ -1,21 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-function JoinRequestPlugin(source, target) {
- this.source = source;
- this.target = target;
-}
-module.exports = JoinRequestPlugin;
-
-JoinRequestPlugin.prototype.apply = function(resolver) {
- var target = this.target;
- resolver.plugin(this.source, function(request, callback) {
- var obj = Object.assign({}, request, {
- path: resolver.join(request.path, request.request),
- relativePath: request.relativePath && resolver.join(request.relativePath, request.request),
- request: undefined
- });
- resolver.doResolve(target, obj, null, callback);
- });
-};
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/LogInfoPlugin.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/LogInfoPlugin.js deleted file mode 100644 index 1ebc837ce..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/LogInfoPlugin.js +++ /dev/null @@ -1,25 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-function LogInfoPlugin(source) {
- this.source = source;
-}
-module.exports = LogInfoPlugin;
-
-LogInfoPlugin.prototype.apply = function(resolver) {
- var source = this.source;
- resolver.plugin(this.source, function(request, callback) {
- if(!callback.log) return callback();
- var log = callback.log;
- var prefix = "[" + source + "] ";
- if(request.path) log(prefix + "Resolving in directory: " + request.path);
- if(request.request) log(prefix + "Resolving request: " + request.request);
- if(request.module) log(prefix + "Request is an module request.");
- if(request.directory) log(prefix + "Request is a directory request.");
- if(request.query) log(prefix + "Resolving request query: " + request.query);
- if(request.descriptionFilePath) log(prefix + "Has description data from " + request.descriptionFilePath);
- if(request.relativePath) log(prefix + "Relative path from description file is: " + request.relativePath);
- callback();
- });
-};
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/MainFieldPlugin.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/MainFieldPlugin.js deleted file mode 100644 index 45ecd4b23..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/MainFieldPlugin.js +++ /dev/null @@ -1,48 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-var path = require("path");
-
-function MainFieldPlugin(source, options, target) {
- this.source = source;
- this.options = options;
- this.target = target;
-}
-module.exports = MainFieldPlugin;
-
-MainFieldPlugin.prototype.apply = function(resolver) {
- var target = this.target;
- var options = this.options;
- resolver.plugin(this.source, function mainField(request, callback) {
- if(request.path !== request.descriptionFileRoot) return callback();
- var content = request.descriptionFileData;
- var filename = path.basename(request.descriptionFilePath);
- var mainModule;
- var field = options.name;
- if(Array.isArray(field)) {
- var current = content;
- for(var j = 0; j < field.length; j++) {
- if(current === null || typeof current !== "object") {
- current = null;
- break;
- }
- current = current[field[j]];
- }
- if(typeof current === "string") {
- mainModule = current;
- }
- } else {
- if(typeof content[field] === "string") {
- mainModule = content[field];
- }
- }
- if(!mainModule) return callback();
- if(options.forceRelative && !/^\.\.?\//.test(mainModule))
- mainModule = "./" + mainModule;
- var obj = Object.assign({}, request, {
- request: mainModule
- });
- return resolver.doResolve(target, obj, "use " + mainModule + " from " + options.name + " in " + filename, callback);
- });
-};
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/ModuleAppendPlugin.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/ModuleAppendPlugin.js deleted file mode 100644 index 55ebcb937..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/ModuleAppendPlugin.js +++ /dev/null @@ -1,35 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-function ModuleAppendPlugin(source, appending, target) {
- this.source = source;
- this.appending = appending;
- this.target = target;
-}
-module.exports = ModuleAppendPlugin;
-
-ModuleAppendPlugin.prototype.apply = function(resolver) {
- var appending = this.appending;
- var target = this.target;
- resolver.plugin(this.source, function(request, callback) {
- var i = request.request.indexOf("/"),
- j = request.request.indexOf("\\");
- var p = i < 0 ? j : j < 0 ? i : i < j ? i : j;
- var moduleName, remainingRequest;
- if(p < 0) {
- moduleName = request.request;
- remainingRequest = "";
- } else {
- moduleName = request.request.substr(0, p);
- remainingRequest = request.request.substr(p);
- }
- if(moduleName === "." || moduleName === "..")
- return callback();
- var moduleFinalName = moduleName + appending;
- var obj = Object.assign({}, request, {
- request: moduleFinalName + remainingRequest
- });
- resolver.doResolve(target, obj, "module variation " + moduleFinalName, callback);
- });
-};
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/ModuleKindPlugin.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/ModuleKindPlugin.js deleted file mode 100644 index e6d920108..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/ModuleKindPlugin.js +++ /dev/null @@ -1,26 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-var createInnerCallback = require("./createInnerCallback");
-
-function ModuleKindPlugin(source, target) {
- this.source = source;
- this.target = target;
-}
-module.exports = ModuleKindPlugin;
-
-ModuleKindPlugin.prototype.apply = function(resolver) {
- var target = this.target;
- resolver.plugin(this.source, function(request, callback) {
- if(!request.module) return callback();
- var obj = Object.assign({}, request);
- delete obj.module;
- resolver.doResolve(target, obj, "resolve as module", createInnerCallback(function(err, result) {
- if(arguments.length > 0) return callback(err, result);
-
- // Don't allow other alternatives
- callback(null, null);
- }, callback));
- });
-};
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/ModulesInHierachicDirectoriesPlugin.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/ModulesInHierachicDirectoriesPlugin.js deleted file mode 100644 index cb942ce94..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/ModulesInHierachicDirectoriesPlugin.js +++ /dev/null @@ -1,46 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-var createInnerCallback = require("./createInnerCallback");
-var forEachBail = require("./forEachBail");
-var getPaths = require("./getPaths");
-
-function ModulesInHierachicDirectoriesPlugin(source, directories, target) {
- this.source = source;
- this.directories = [].concat(directories);
- this.target = target;
-}
-module.exports = ModulesInHierachicDirectoriesPlugin;
-
-ModulesInHierachicDirectoriesPlugin.prototype.apply = function(resolver) {
- var directories = this.directories;
- var target = this.target;
- resolver.plugin(this.source, function(request, callback) {
- var fs = this.fileSystem;
- var topLevelCallback = callback;
- var addrs = getPaths(request.path).paths.map(function(p) {
- return directories.map(function(d) {
- return this.join(p, d);
- }, this);
- }, this).reduce(function(array, p) {
- array.push.apply(array, p);
- return array;
- }, []);
- forEachBail(addrs, function(addr, callback) {
- fs.stat(addr, function(err, stat) {
- if(!err && stat && stat.isDirectory()) {
- var obj = Object.assign({}, request, {
- path: addr,
- request: "./" + request.request
- });
- var message = "looking for modules in " + addr;
- return resolver.doResolve(target, obj, message, createInnerCallback(callback, topLevelCallback));
- }
- if(topLevelCallback.log) topLevelCallback.log(addr + " doesn't exist or is not a directory");
- if(topLevelCallback.missing) topLevelCallback.missing.push(addr);
- return callback();
- });
- }, callback);
- });
-};
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/ModulesInRootPlugin.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/ModulesInRootPlugin.js deleted file mode 100644 index 1d7de20fb..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/ModulesInRootPlugin.js +++ /dev/null @@ -1,22 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-function ModulesInRootPlugin(source, path, target) {
- this.source = source;
- this.path = path;
- this.target = target;
-}
-module.exports = ModulesInRootPlugin;
-
-ModulesInRootPlugin.prototype.apply = function(resolver) {
- var target = this.target;
- var path = this.path;
- resolver.plugin(this.source, function(request, callback) {
- var obj = Object.assign({}, request, {
- path: path,
- request: "./" + request.request
- });
- resolver.doResolve(target, obj, "looking for modules in " + path, callback, true);
- });
-};
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/NextPlugin.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/NextPlugin.js deleted file mode 100644 index 0db218c81..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/NextPlugin.js +++ /dev/null @@ -1,16 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-function NextPlugin(source, target) {
- this.source = source;
- this.target = target;
-}
-module.exports = NextPlugin;
-
-NextPlugin.prototype.apply = function(resolver) {
- var target = this.target;
- resolver.plugin(this.source, function(request, callback) {
- resolver.doResolve(target, request, null, callback);
- });
-};
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/NodeJsInputFileSystem.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/NodeJsInputFileSystem.js deleted file mode 100644 index 28c78ca8a..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/NodeJsInputFileSystem.js +++ /dev/null @@ -1,29 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-var fs = require("graceful-fs");
-
-function NodeJsInputFileSystem() {}
-module.exports = NodeJsInputFileSystem;
-
-NodeJsInputFileSystem.prototype.stat = fs.stat.bind(fs);
-NodeJsInputFileSystem.prototype.readdir = function readdir(path, callback) {
- fs.readdir(path, function(err, files) {
- callback(err, files && files.map(function(file) {
- return file.normalize ? file.normalize("NFC") : file;
- }));
- });
-};
-NodeJsInputFileSystem.prototype.readFile = fs.readFile.bind(fs);
-NodeJsInputFileSystem.prototype.readlink = fs.readlink.bind(fs);
-
-NodeJsInputFileSystem.prototype.statSync = fs.statSync.bind(fs);
-NodeJsInputFileSystem.prototype.readdirSync = function readdirSync(path) {
- var files = fs.readdirSync(path);
- return files && files.map(function(file) {
- return file.normalize ? file.normalize("NFC") : file;
- });
-};
-NodeJsInputFileSystem.prototype.readFileSync = fs.readFileSync.bind(fs);
-NodeJsInputFileSystem.prototype.readlinkSync = fs.readlinkSync.bind(fs);
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/ParsePlugin.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/ParsePlugin.js deleted file mode 100644 index f4117fac9..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/ParsePlugin.js +++ /dev/null @@ -1,27 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-function ParsePlugin(source, target) {
- this.source = source;
- this.target = target;
-}
-module.exports = ParsePlugin;
-
-ParsePlugin.prototype.apply = function(resolver) {
- var target = this.target;
- resolver.plugin(this.source, function(request, callback) {
- var parsed = resolver.parse(request.request);
- var obj = Object.assign({}, request, parsed);
- if(request.query && !parsed.query) {
- obj.query = request.query;
- }
- if(parsed && callback.log) {
- if(parsed.module)
- callback.log("Parsed request is a module");
- if(parsed.directory)
- callback.log("Parsed request is a directory");
- }
- resolver.doResolve(target, obj, null, callback);
- });
-};
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/Resolver.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/Resolver.js deleted file mode 100644 index 35266b172..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/Resolver.js +++ /dev/null @@ -1,227 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-var Tapable = require("tapable");
-var createInnerCallback = require("./createInnerCallback");
-
-function Resolver(fileSystem) {
- Tapable.call(this);
- this.fileSystem = fileSystem;
-}
-module.exports = Resolver;
-
-Resolver.prototype = Object.create(Tapable.prototype);
-
-Resolver.prototype.constructor = Resolver;
-
-Resolver.prototype.resolveSync = function resolveSync(context, path, request) {
- var err, result, sync = false;
- this.resolve(context, path, request, function(e, r) {
- err = e;
- result = r;
- sync = true;
- });
- if(!sync) throw new Error("Cannot 'resolveSync' because the fileSystem is not sync. Use 'resolve'!");
- if(err) throw err;
- return result;
-};
-
-Resolver.prototype.resolve = function resolve(context, path, request, callback) {
- if(arguments.length === 3) {
- throw new Error("Signature changed: context parameter added");
- }
- var resolver = this;
- var obj = {
- context: context,
- path: path,
- request: request
- };
-
- var localMissing;
- var log;
- var message = "resolve '" + request + "' in '" + path + "'";
-
- function writeLog(msg) {
- log.push(msg);
- }
-
- function logAsString() {
- return log.join("\n");
- }
-
- function onError(err, result) {
- if(callback.log) {
- for(var i = 0; i < log.length; i++)
- callback.log(log[i]);
- }
-
- if(err) return callback(err);
-
- var error = new Error("Can't " + message);
- error.details = logAsString();
- error.missing = localMissing;
- resolver.applyPlugins("no-resolve", obj, error);
- return callback(error);
- }
-
- function onResolve(err, result) {
- if(!err && result) {
- return callback(null, result.path === false ? false : result.path + (result.query || ""), result);
- }
-
- localMissing = [];
- log = [];
-
- return resolver.doResolve("resolve", obj, message, createInnerCallback(onError, {
- log: writeLog,
- missing: localMissing,
- stack: callback.stack
- }));
- }
-
- onResolve.missing = callback.missing;
- onResolve.stack = callback.stack;
-
- return this.doResolve("resolve", obj, message, onResolve);
-};
-
-Resolver.prototype.doResolve = function doResolve(type, request, message, callback) {
- var resolver = this;
- var stackLine = type + ": (" + request.path + ") " +
- (request.request || "") + (request.query || "") +
- (request.directory ? " directory" : "") +
- (request.module ? " module" : "");
- var newStack = [stackLine];
- if(callback.stack) {
- newStack = callback.stack.concat(newStack);
- if(callback.stack.indexOf(stackLine) >= 0) {
- // Prevent recursion
- var recursionError = new Error("Recursion in resolving\nStack:\n " + newStack.join("\n "));
- recursionError.recursion = true;
- if(callback.log) callback.log("abort resolving because of recursion");
- return callback(recursionError);
- }
- }
- resolver.applyPlugins("resolve-step", type, request);
-
- var beforePluginName = "before-" + type;
- if(resolver.hasPlugins(beforePluginName)) {
- resolver.applyPluginsAsyncSeriesBailResult1(beforePluginName, request, createInnerCallback(beforeInnerCallback, {
- log: callback.log,
- missing: callback.missing,
- stack: newStack
- }, message && ("before " + message), true));
- } else {
- runNormal();
- }
-
- function beforeInnerCallback(err, result) {
- if(arguments.length > 0) {
- if(err) return callback(err);
- if(result) return callback(null, result);
- return callback();
- }
- runNormal();
- }
-
- function runNormal() {
- if(resolver.hasPlugins(type)) {
- return resolver.applyPluginsAsyncSeriesBailResult1(type, request, createInnerCallback(innerCallback, {
- log: callback.log,
- missing: callback.missing,
- stack: newStack
- }, message));
- } else {
- runAfter();
- }
- }
-
- function innerCallback(err, result) {
- if(arguments.length > 0) {
- if(err) return callback(err);
- if(result) return callback(null, result);
- return callback();
- }
- runAfter();
- }
-
- function runAfter() {
- var afterPluginName = "after-" + type;
- if(resolver.hasPlugins(afterPluginName)) {
- return resolver.applyPluginsAsyncSeriesBailResult1(afterPluginName, request, createInnerCallback(afterInnerCallback, {
- log: callback.log,
- missing: callback.missing,
- stack: newStack
- }, message && ("after " + message), true));
- } else {
- callback();
- }
- }
-
- function afterInnerCallback(err, result) {
- if(arguments.length > 0) {
- if(err) return callback(err);
- if(result) return callback(null, result);
- return callback();
- }
- return callback();
- }
-};
-
-Resolver.prototype.parse = function parse(identifier) {
- if(identifier === "") return null;
- var part = {
- request: "",
- query: "",
- module: false,
- directory: false,
- file: false
- };
- var idxQuery = identifier.indexOf("?");
- if(idxQuery === 0) {
- part.query = identifier;
- } else if(idxQuery > 0) {
- part.request = identifier.slice(0, idxQuery);
- part.query = identifier.slice(idxQuery);
- } else {
- part.request = identifier;
- }
- if(part.request) {
- part.module = this.isModule(part.request);
- part.directory = this.isDirectory(part.request);
- if(part.directory) {
- part.request = part.request.substr(0, part.request.length - 1);
- }
- }
- return part;
-};
-
-var notModuleRegExp = /^\.$|^\.[\\\/]|^\.\.$|^\.\.[\/\\]|^\/|^[A-Z]:[\\\/]/i;
-Resolver.prototype.isModule = function isModule(path) {
- return !notModuleRegExp.test(path);
-};
-
-var directoryRegExp = /[\/\\]$/i;
-Resolver.prototype.isDirectory = function isDirectory(path) {
- return directoryRegExp.test(path);
-};
-
-var memoryFsJoin = require("memory-fs/lib/join");
-var memoizedJoin = new Map();
-Resolver.prototype.join = function(path, request) {
- var cacheEntry;
- var pathCache = memoizedJoin.get(path);
- if(typeof pathCache === "undefined") {
- memoizedJoin.set(path, pathCache = new Map());
- } else {
- cacheEntry = pathCache.get(request);
- if(typeof cacheEntry !== "undefined")
- return cacheEntry;
- }
- cacheEntry = memoryFsJoin(path, request);
- pathCache.set(request, cacheEntry);
- return cacheEntry;
-};
-
-Resolver.prototype.normalize = require("memory-fs/lib/normalize");
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/ResolverFactory.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/ResolverFactory.js deleted file mode 100644 index cd167aaf7..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/ResolverFactory.js +++ /dev/null @@ -1,273 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-var Resolver = require("./Resolver");
-
-var SyncAsyncFileSystemDecorator = require("./SyncAsyncFileSystemDecorator");
-
-var ParsePlugin = require("./ParsePlugin");
-var DescriptionFilePlugin = require("./DescriptionFilePlugin");
-var NextPlugin = require("./NextPlugin");
-var TryNextPlugin = require("./TryNextPlugin");
-var ModuleKindPlugin = require("./ModuleKindPlugin");
-var FileKindPlugin = require("./FileKindPlugin");
-var JoinRequestPlugin = require("./JoinRequestPlugin");
-var ModulesInHierachicDirectoriesPlugin = require("./ModulesInHierachicDirectoriesPlugin");
-var ModulesInRootPlugin = require("./ModulesInRootPlugin");
-var AliasPlugin = require("./AliasPlugin");
-var AliasFieldPlugin = require("./AliasFieldPlugin");
-var ConcordExtensionsPlugin = require("./ConcordExtensionsPlugin");
-var ConcordMainPlugin = require("./ConcordMainPlugin");
-var ConcordModulesPlugin = require("./ConcordModulesPlugin");
-var DirectoryExistsPlugin = require("./DirectoryExistsPlugin");
-var FileExistsPlugin = require("./FileExistsPlugin");
-var SymlinkPlugin = require("./SymlinkPlugin");
-var MainFieldPlugin = require("./MainFieldPlugin");
-var UseFilePlugin = require("./UseFilePlugin");
-var AppendPlugin = require("./AppendPlugin");
-var ResultPlugin = require("./ResultPlugin");
-var ModuleAppendPlugin = require("./ModuleAppendPlugin");
-var UnsafeCachePlugin = require("./UnsafeCachePlugin");
-
-exports.createResolver = function(options) {
-
- //// OPTIONS ////
-
- // A list of directories to resolve modules from, can be absolute path or folder name
- var modules = options.modules || ["node_modules"];
-
- // A list of description files to read from
- var descriptionFiles = options.descriptionFiles || ["package.json"];
-
- // A list of additional resolve plugins which should be applied
- // The slice is there to create a copy, because otherwise pushing into plugins
- // changes the original options.plugins array, causing duplicate plugins
- var plugins = (options.plugins && options.plugins.slice()) || [];
-
- // A list of main fields in description files
- var mainFields = options.mainFields || ["main"];
-
- // A list of alias fields in description files
- var aliasFields = options.aliasFields || [];
-
- // A list of main files in directories
- var mainFiles = options.mainFiles || ["index"];
-
- // A list of extensions which should be tried for files
- var extensions = options.extensions || [".js", ".json", ".node"];
-
- // Enforce that a extension from extensions must be used
- var enforceExtension = options.enforceExtension || false;
-
- // A list of module extensions which should be tried for modules
- var moduleExtensions = options.moduleExtensions || [];
-
- // Enforce that a extension from moduleExtensions must be used
- var enforceModuleExtension = options.enforceModuleExtension || false;
-
- // A list of module alias configurations or an object which maps key to value
- var alias = options.alias || [];
-
- // Resolve symlinks to their symlinked location
- var symlinks = typeof options.symlinks !== "undefined" ? options.symlinks : true;
-
- // Resolve to a context instead of a file
- var resolveToContext = options.resolveToContext || false;
-
- // Use this cache object to unsafely cache the successful requests
- var unsafeCache = options.unsafeCache || false;
-
- // Whether or not the unsafeCache should include request context as part of the cache key.
- var cacheWithContext = typeof options.cacheWithContext !== "undefined" ? options.cacheWithContext : true;
-
- // A function which decides whether a request should be cached or not.
- // an object is passed with `path` and `request` properties.
- var cachePredicate = options.cachePredicate || function() {
- return true;
- };
-
- // The file system which should be used
- var fileSystem = options.fileSystem;
-
- // Use only the sync variants of the file system calls
- var useSyncFileSystemCalls = options.useSyncFileSystemCalls;
-
- // A prepared Resolver to which the plugins are attached
- var resolver = options.resolver;
-
- //// options processing ////
-
- if(!resolver) {
- resolver = new Resolver(useSyncFileSystemCalls ? new SyncAsyncFileSystemDecorator(fileSystem) : fileSystem);
- }
-
- extensions = [].concat(extensions);
- moduleExtensions = [].concat(moduleExtensions);
-
- modules = mergeFilteredToArray([].concat(modules), function(item) {
- return !isAbsolutePath(item);
- });
-
- mainFields = mainFields.map(function(item) {
- if(typeof item === "string") {
- item = {
- name: item,
- forceRelative: true
- };
- }
- return item;
- });
-
- if(typeof alias === "object" && !Array.isArray(alias)) {
- alias = Object.keys(alias).map(function(key) {
- var onlyModule = false;
- var obj = alias[key];
- if(/\$$/.test(key)) {
- onlyModule = true;
- key = key.substr(0, key.length - 1);
- }
- if(typeof obj === "string") {
- obj = {
- alias: obj
- };
- }
- obj = Object.assign({
- name: key,
- onlyModule: onlyModule
- }, obj);
- return obj;
- });
- }
-
- if(unsafeCache && typeof unsafeCache !== "object") {
- unsafeCache = {};
- }
-
- //// pipeline ////
-
- // resolve
- if(unsafeCache) {
- plugins.push(new UnsafeCachePlugin("resolve", cachePredicate, unsafeCache, cacheWithContext, "new-resolve"));
- plugins.push(new ParsePlugin("new-resolve", "parsed-resolve"));
- } else {
- plugins.push(new ParsePlugin("resolve", "parsed-resolve"));
- }
-
- // parsed-resolve
- plugins.push(new DescriptionFilePlugin("parsed-resolve", descriptionFiles, "described-resolve"));
- plugins.push(new NextPlugin("after-parsed-resolve", "described-resolve"));
-
- // described-resolve
- alias.forEach(function(item) {
- plugins.push(new AliasPlugin("described-resolve", item, "resolve"));
- });
- plugins.push(new ConcordModulesPlugin("described-resolve", {}, "resolve"));
- aliasFields.forEach(function(item) {
- plugins.push(new AliasFieldPlugin("described-resolve", item, "resolve"));
- });
- plugins.push(new ModuleKindPlugin("after-described-resolve", "raw-module"));
- plugins.push(new JoinRequestPlugin("after-described-resolve", "relative"));
-
- // raw-module
- moduleExtensions.forEach(function(item) {
- plugins.push(new ModuleAppendPlugin("raw-module", item, "module"));
- });
- if(!enforceModuleExtension)
- plugins.push(new TryNextPlugin("raw-module", null, "module"));
-
- // module
- modules.forEach(function(item) {
- if(Array.isArray(item))
- plugins.push(new ModulesInHierachicDirectoriesPlugin("module", item, "resolve"));
- else
- plugins.push(new ModulesInRootPlugin("module", item, "resolve"));
- });
-
- // relative
- plugins.push(new DescriptionFilePlugin("relative", descriptionFiles, "described-relative"));
- plugins.push(new NextPlugin("after-relative", "described-relative"));
-
- // described-relative
- plugins.push(new FileKindPlugin("described-relative", "raw-file"));
- plugins.push(new TryNextPlugin("described-relative", "as directory", "directory"));
-
- // directory
- plugins.push(new DirectoryExistsPlugin("directory", "existing-directory"));
-
- if(resolveToContext) {
-
- // existing-directory
- plugins.push(new NextPlugin("existing-directory", "resolved"));
-
- } else {
-
- // existing-directory
- plugins.push(new ConcordMainPlugin("existing-directory", {}, "resolve"));
- mainFields.forEach(function(item) {
- plugins.push(new MainFieldPlugin("existing-directory", item, "resolve"));
- });
- mainFiles.forEach(function(item) {
- plugins.push(new UseFilePlugin("existing-directory", item, "undescribed-raw-file"));
- });
-
- // undescribed-raw-file
- plugins.push(new DescriptionFilePlugin("undescribed-raw-file", descriptionFiles, "raw-file"));
- plugins.push(new NextPlugin("after-undescribed-raw-file", "raw-file"));
-
- // raw-file
- if(!enforceExtension)
- plugins.push(new TryNextPlugin("raw-file", "no extension", "file"));
- plugins.push(new ConcordExtensionsPlugin("raw-file", {}, "file"));
- extensions.forEach(function(item) {
- plugins.push(new AppendPlugin("raw-file", item, "file"));
- });
-
- // file
- alias.forEach(function(item) {
- plugins.push(new AliasPlugin("file", item, "resolve"));
- });
- plugins.push(new ConcordModulesPlugin("file", {}, "resolve"));
- aliasFields.forEach(function(item) {
- plugins.push(new AliasFieldPlugin("file", item, "resolve"));
- });
- if(symlinks)
- plugins.push(new SymlinkPlugin("file", "relative"));
- plugins.push(new FileExistsPlugin("file", "existing-file"));
-
- // existing-file
- plugins.push(new NextPlugin("existing-file", "resolved"));
-
- }
-
- // resolved
- plugins.push(new ResultPlugin("resolved"));
-
- //// RESOLVER ////
-
- plugins.forEach(function(plugin) {
- resolver.apply(plugin);
- });
- return resolver;
-};
-
-function mergeFilteredToArray(array, filter) {
- return array.reduce(function(array, item) {
- if(filter(item)) {
- var lastElement = array[array.length - 1];
- if(Array.isArray(lastElement)) {
- lastElement.push(item);
- } else {
- array.push([item]);
- }
- return array;
- } else {
- array.push(item);
- return array;
- }
- }, []);
-}
-
-function isAbsolutePath(path) {
- return /^[A-Z]:|^\//.test(path);
-}
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/ResultPlugin.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/ResultPlugin.js deleted file mode 100644 index 7e262cc17..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/ResultPlugin.js +++ /dev/null @@ -1,18 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-function ResultPlugin(source) {
- this.source = source;
-}
-module.exports = ResultPlugin;
-
-ResultPlugin.prototype.apply = function(resolver) {
- resolver.plugin(this.source, function(request, callback) {
- var obj = Object.assign({}, request);
- resolver.applyPluginsAsyncSeries1("result", obj, function(err) {
- if(err) return callback(err);
- callback(null, obj);
- });
- });
-};
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/SymlinkPlugin.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/SymlinkPlugin.js deleted file mode 100644 index c79da04b2..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/SymlinkPlugin.js +++ /dev/null @@ -1,47 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-var getPaths = require("./getPaths");
-var forEachBail = require("./forEachBail");
-
-function SymlinkPlugin(source, target) {
- this.source = source;
- this.target = target;
-}
-module.exports = SymlinkPlugin;
-
-SymlinkPlugin.prototype.apply = function(resolver) {
- var target = this.target;
- resolver.plugin(this.source, function(request, callback) {
- var _this = this;
- var fs = _this.fileSystem;
- var pathsResult = getPaths(request.path);
- var pathSeqments = pathsResult.seqments;
- var paths = pathsResult.paths;
-
- var containsSymlink = false;
- forEachBail.withIndex(paths, function(path, idx, callback) {
- fs.readlink(path, function(err, result) {
- if(!err && result) {
- pathSeqments[idx] = result;
- containsSymlink = true;
- // Shortcut when absolute symlink found
- if(/^(\/|[a-zA-z]:($|\\))/.test(result))
- return callback(null, idx);
- }
- callback();
- });
- }, function(err, idx) {
- if(!containsSymlink) return callback();
- var resultSeqments = typeof idx === "number" ? pathSeqments.slice(0, idx + 1) : pathSeqments.slice();
- var result = resultSeqments.reverse().reduce(function(a, b) {
- return _this.join(a, b);
- });
- var obj = Object.assign({}, request, {
- path: result
- });
- resolver.doResolve(target, obj, "resolved symlink to " + result, callback);
- });
- });
-};
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/SyncAsyncFileSystemDecorator.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/SyncAsyncFileSystemDecorator.js deleted file mode 100644 index f5b26c465..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/SyncAsyncFileSystemDecorator.js +++ /dev/null @@ -1,58 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-function SyncAsyncFileSystemDecorator(fs) {
- this.fs = fs;
- if(fs.statSync) {
- this.stat = function(arg, callback) {
- try {
- var result = fs.statSync(arg);
- } catch(e) {
- return callback(e);
- }
- callback(null, result);
- };
- }
- if(fs.readdirSync) {
- this.readdir = function(arg, callback) {
- try {
- var result = fs.readdirSync(arg);
- } catch(e) {
- return callback(e);
- }
- callback(null, result);
- };
- }
- if(fs.readFileSync) {
- this.readFile = function(arg, callback) {
- try {
- var result = fs.readFileSync(arg);
- } catch(e) {
- return callback(e);
- }
- callback(null, result);
- };
- }
- if(fs.readlinkSync) {
- this.readlink = function(arg, callback) {
- try {
- var result = fs.readlinkSync(arg);
- } catch(e) {
- return callback(e);
- }
- callback(null, result);
- };
- }
- if(fs.readJsonSync) {
- this.readJson = function(arg, callback) {
- try {
- var result = fs.readJsonSync(arg);
- } catch(e) {
- return callback(e);
- }
- callback(null, result);
- };
- }
-}
-module.exports = SyncAsyncFileSystemDecorator;
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/TryNextPlugin.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/TryNextPlugin.js deleted file mode 100644 index e4c9f9c0f..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/TryNextPlugin.js +++ /dev/null @@ -1,18 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-function TryNextPlugin(source, message, target) {
- this.source = source;
- this.message = message;
- this.target = target;
-}
-module.exports = TryNextPlugin;
-
-TryNextPlugin.prototype.apply = function(resolver) {
- var target = this.target;
- var message = this.message;
- resolver.plugin(this.source, function(request, callback) {
- resolver.doResolve(target, request, message, callback);
- });
-};
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/UnsafeCachePlugin.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/UnsafeCachePlugin.js deleted file mode 100644 index ed07fd561..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/UnsafeCachePlugin.js +++ /dev/null @@ -1,43 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-var createInnerCallback = require("./createInnerCallback");
-
-function UnsafeCachePlugin(source, filterPredicate, cache, withContext, target) {
- this.source = source;
- this.filterPredicate = filterPredicate;
- this.withContext = withContext;
- this.cache = cache || {};
- this.target = target;
-}
-module.exports = UnsafeCachePlugin;
-
-function getCacheId(request, withContext) {
- return JSON.stringify({
- context: withContext ? request.context : "",
- path: request.path,
- query: request.query,
- request: request.request
- });
-}
-
-UnsafeCachePlugin.prototype.apply = function(resolver) {
- var filterPredicate = this.filterPredicate;
- var cache = this.cache;
- var target = this.target;
- var withContext = this.withContext;
- resolver.plugin(this.source, function(request, callback) {
- if(!filterPredicate(request)) return callback();
- var cacheId = getCacheId(request, withContext);
- var cacheEntry = cache[cacheId];
- if(cacheEntry) {
- return callback(null, cacheEntry);
- }
- resolver.doResolve(target, request, null, createInnerCallback(function(err, result) {
- if(err) return callback(err);
- if(result) return callback(null, cache[cacheId] = result);
- callback();
- }, callback));
- });
-};
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/UseFilePlugin.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/UseFilePlugin.js deleted file mode 100644 index 2413824f4..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/UseFilePlugin.js +++ /dev/null @@ -1,23 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-function UseFilePlugin(source, filename, target) {
- this.source = source;
- this.filename = filename;
- this.target = target;
-}
-module.exports = UseFilePlugin;
-
-UseFilePlugin.prototype.apply = function(resolver) {
- var filename = this.filename;
- var target = this.target;
- resolver.plugin(this.source, function(request, callback) {
- var filePath = resolver.join(request.path, filename);
- var obj = Object.assign({}, request, {
- path: filePath,
- relativePath: request.relativePath && resolver.join(request.relativePath, filename)
- });
- resolver.doResolve(target, obj, "using path: " + filePath, callback);
- });
-};
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/concord.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/concord.js deleted file mode 100644 index c8db37940..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/concord.js +++ /dev/null @@ -1,189 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-var globToRegExp = require("./globToRegExp").globToRegExp;
-
-function parseType(type) {
- var items = type.split("+");
- var t = items.shift();
- return {
- type: t === "*" ? null : t,
- features: items
- };
-}
-
-function isTypeMatched(baseType, testedType) {
- if(typeof baseType === "string") baseType = parseType(baseType);
- if(typeof testedType === "string") testedType = parseType(testedType);
- if(testedType.type && testedType.type !== baseType.type) return false;
- return testedType.features.every(function(requiredFeature) {
- return baseType.features.indexOf(requiredFeature) >= 0;
- });
-}
-
-function isResourceTypeMatched(baseType, testedType) {
- baseType = baseType.split("/");
- testedType = testedType.split("/");
- if(baseType.length !== testedType.length) return false;
- for(var i = 0; i < baseType.length; i++) {
- if(!isTypeMatched(baseType[i], testedType[i]))
- return false;
- }
- return true;
-}
-
-function isResourceTypeSupported(context, type) {
- return context.supportedResourceTypes && context.supportedResourceTypes.some(function(supportedType) {
- return isResourceTypeMatched(supportedType, type);
- });
-}
-
-function isEnvironment(context, env) {
- return context.environments && context.environments.every(function(environment) {
- return isTypeMatched(environment, env);
- });
-}
-
-var globCache = {};
-
-function getGlobRegExp(glob) {
- var regExp = globCache[glob] || (globCache[glob] = globToRegExp(glob));
- return regExp;
-}
-
-function matchGlob(glob, relativePath) {
- var regExp = getGlobRegExp(glob);
- return regExp.exec(relativePath);
-}
-
-function isGlobMatched(glob, relativePath) {
- return !!matchGlob(glob, relativePath);
-}
-
-function isConditionMatched(context, condition) {
- var items = condition.split("|");
- return items.some(function testFn(item) {
- item = item.trim();
- var inverted = /^!/.test(item);
- if(inverted) return !testFn(item.substr(1));
- if(/^[a-z]+:/.test(item)) {
- // match named condition
- var match = /^([a-z]+):\s*/.exec(item);
- var value = item.substr(match[0].length);
- var name = match[1];
- switch(name) {
- case "referrer":
- return isGlobMatched(value, context.referrer);
- default:
- return false;
- }
- } else if(item.indexOf("/") >= 0) {
- // match supported type
- return isResourceTypeSupported(context, item);
- } else {
- // match environment
- return isEnvironment(context, item);
- }
- });
-}
-
-function isKeyMatched(context, key) {
- while(true) { //eslint-disable-line
- var match = /^\[([^\]]+)\]\s*/.exec(key);
- if(!match) return key;
- key = key.substr(match[0].length);
- var condition = match[1];
- if(!isConditionMatched(context, condition)) {
- return false;
- }
- }
-}
-
-function getField(context, configuration, field) {
- var value;
- Object.keys(configuration).forEach(function(key) {
- var pureKey = isKeyMatched(context, key);
- if(pureKey === field) {
- value = configuration[key];
- }
- });
- return value;
-}
-
-function getMain(context, configuration) {
- return getField(context, configuration, "main");
-}
-
-function getExtensions(context, configuration) {
- return getField(context, configuration, "extensions");
-}
-
-function matchModule(context, configuration, request) {
- var modulesField = getField(context, configuration, "modules");
- if(!modulesField) return request;
- var newRequest = request;
- var keys = Object.keys(modulesField);
- var iteration = 0;
- for(var i = 0; i < keys.length; i++) {
- var key = keys[i];
- var pureKey = isKeyMatched(context, key);
- var match = matchGlob(pureKey, newRequest);
- if(match) {
- var value = modulesField[key];
- if(typeof value !== "string") {
- return value;
- } else if(/^\(.+\)$/.test(pureKey)) {
- newRequest = newRequest.replace(getGlobRegExp(pureKey), value);
- } else {
- var index = 1;
- newRequest = value.replace(/(\/?\*)?\*/g, replaceMatcher);
- }
- i = -1;
- if(iteration++ > keys.length) {
- throw new Error("Request '" + request + "' matches recursively");
- }
- }
- }
- return newRequest;
-
- function replaceMatcher(find) {
- switch(find) {
- case "/**":
- var m = match[index++];
- return m ? "/" + m : "";
- case "**":
- case "*":
- return match[index++];
- }
- }
-}
-
-function matchType(context, configuration, relativePath) {
- var typesField = getField(context, configuration, "types");
- if(!typesField) return undefined;
- var type;
- Object.keys(typesField).forEach(function(key) {
- var pureKey = isKeyMatched(context, key);
- if(isGlobMatched(pureKey, relativePath)) {
- var value = typesField[key];
- if(!type && /\/\*$/.test(value))
- throw new Error("value ('" + value + "') of key '" + key + "' contains '*', but there is no previous value defined");
- type = value.replace(/\/\*$/, "/" + type);
- }
- });
- return type;
-}
-
-exports.parseType = parseType;
-exports.isTypeMatched = isTypeMatched;
-exports.isResourceTypeSupported = isResourceTypeSupported;
-exports.isEnvironment = isEnvironment;
-exports.isGlobMatched = isGlobMatched;
-exports.isConditionMatched = isConditionMatched;
-exports.isKeyMatched = isKeyMatched;
-exports.getField = getField;
-exports.getMain = getMain;
-exports.getExtensions = getExtensions;
-exports.matchModule = matchModule;
-exports.matchType = matchType;
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/createInnerCallback.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/createInnerCallback.js deleted file mode 100644 index 0acea4662..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/createInnerCallback.js +++ /dev/null @@ -1,41 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-module.exports = function createInnerCallback(callback, options, message, messageOptional) {
- var log = options.log;
- if(!log) {
- if(options.stack !== callback.stack) {
- var callbackWrapper = function callbackWrapper() {
- return callback.apply(this, arguments);
- };
- callbackWrapper.stack = options.stack;
- callbackWrapper.missing = options.missing;
- return callbackWrapper;
- }
- return callback;
- }
-
- function loggingCallbackWrapper() {
- var i;
- if(message) {
- if(!messageOptional || theLog.length > 0) {
- log(message);
- for(i = 0; i < theLog.length; i++)
- log(" " + theLog[i]);
- }
- } else {
- for(i = 0; i < theLog.length; i++)
- log(theLog[i]);
- }
- return callback.apply(this, arguments);
-
- }
- var theLog = [];
- loggingCallbackWrapper.log = function writeLog(msg) {
- theLog.push(msg);
- };
- loggingCallbackWrapper.stack = options.stack;
- loggingCallbackWrapper.missing = options.missing;
- return loggingCallbackWrapper;
-};
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/forEachBail.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/forEachBail.js deleted file mode 100644 index 59e98ce91..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/forEachBail.js +++ /dev/null @@ -1,65 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-module.exports = function forEachBail(array, iterator, callback) {
- if(array.length === 0) return callback();
- var currentPos = array.length;
- var currentResult;
- var done = [];
- for(var i = 0; i < array.length; i++) {
- var itCb = createIteratorCallback(i);
- iterator(array[i], itCb);
- if(currentPos === 0) break;
- }
-
- function createIteratorCallback(i) {
- return function() {
- if(i >= currentPos) return; // ignore
- var args = Array.prototype.slice.call(arguments);
- done.push(i);
- if(args.length > 0) {
- currentPos = i + 1;
- done = done.filter(function(item) {
- return item <= i;
- });
- currentResult = args;
- }
- if(done.length === currentPos) {
- callback.apply(null, currentResult);
- currentPos = 0;
- }
- };
- }
-};
-
-module.exports.withIndex = function forEachBailWithIndex(array, iterator, callback) {
- if(array.length === 0) return callback();
- var currentPos = array.length;
- var currentResult;
- var done = [];
- for(var i = 0; i < array.length; i++) {
- var itCb = createIteratorCallback(i);
- iterator(array[i], i, itCb);
- if(currentPos === 0) break;
- }
-
- function createIteratorCallback(i) {
- return function() {
- if(i >= currentPos) return; // ignore
- var args = Array.prototype.slice.call(arguments);
- done.push(i);
- if(args.length > 0) {
- currentPos = i + 1;
- done = done.filter(function(item) {
- return item <= i;
- });
- currentResult = args;
- }
- if(done.length === currentPos) {
- callback.apply(null, currentResult);
- currentPos = 0;
- }
- };
- }
-};
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/getInnerRequest.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/getInnerRequest.js deleted file mode 100644 index 3f6ac148c..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/getInnerRequest.js +++ /dev/null @@ -1,22 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-module.exports = function getInnerRequest(resolver, request) {
- if(typeof request.__innerRequest === "string" &&
- request.__innerRequest_request === request.request &&
- request.__innerRequest_relativePath === request.relativePath)
- return request.__innerRequest;
- var innerRequest;
- if(request.request) {
- innerRequest = request.request;
- if(/^\.\.?\//.test(innerRequest) && request.relativePath) {
- innerRequest = resolver.join(request.relativePath, innerRequest);
- }
- } else {
- innerRequest = request.relativePath;
- }
- request.__innerRequest_request = request.request;
- request.__innerRequest_relativePath = request.relativePath;
- return request.__innerRequest = innerRequest;
-};
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/getPaths.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/getPaths.js deleted file mode 100644 index 695fbcd5f..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/getPaths.js +++ /dev/null @@ -1,33 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-module.exports = function getPaths(path) {
- var parts = path.split(/(.*?[\\\/]+)/);
- var paths = [path];
- var seqments = [parts[parts.length - 1]];
- var part = parts[parts.length - 1];
- path = path.substr(0, path.length - part.length - 1);
- paths.push(path);
- for(var i = parts.length - 2; i > 2; i -= 2) {
- part = parts[i];
- path = path.substr(0, path.length - part.length) || "/";
- paths.push(path);
- seqments.push(part.substr(0, part.length - 1));
- }
- part = parts[1];
- seqments.push(part.length > 1 ? part.substr(0, part.length - 1) : part);
- return {
- paths: paths,
- seqments: seqments
- };
-};
-
-module.exports.basename = function basename(path) {
- var i = path.lastIndexOf("/"),
- j = path.lastIndexOf("\\");
- var p = i < 0 ? j : j < 0 ? i : i < j ? j : i;
- if(p < 0) return null;
- var s = path.substr(p + 1);
- return s;
-};
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/globToRegExp.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/globToRegExp.js deleted file mode 100644 index 7b97a6924..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/globToRegExp.js +++ /dev/null @@ -1,188 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-function globToRegExp(glob) {
- // * [^\\\/]*
- // /**/ /.+/
- // ^* \./.+ (concord special)
- // ? [^\\\/]
- // [!...] [^...]
- // [^...] [^...]
- // / [\\\/]
- // {...,...} (...|...)
- // ?(...|...) (...|...)?
- // +(...|...) (...|...)+
- // *(...|...) (...|...)*
- // @(...|...) (...|...)
- if(/^\(.+\)$/.test(glob)) {
- // allow to pass an RegExp in brackets
- return new RegExp(glob.substr(1, glob.length - 2));
- }
- var tokens = tokenize(glob);
- var process = createRoot();
- var regExpStr = tokens.map(process).join("");
- return new RegExp("^" + regExpStr + "$");
-}
-
-var SIMPLE_TOKENS = {
- "@(": "one",
- "?(": "zero-one",
- "+(": "one-many",
- "*(": "zero-many",
- "|": "segment-sep",
- "/**/": "any-path-segments",
- "**": "any-path",
- "*": "any-path-segment",
- "?": "any-char",
- "{": "or",
- "/": "path-sep",
- ",": "comma",
- ")": "closing-segment",
- "}": "closing-or"
-};
-
-function tokenize(glob) {
- return glob.split(/([@?+*]\(|\/\*\*\/|\*\*|[?*]|\[[\!\^]?(?:[^\]\\]|\\.)+\]|\{|,|\/|[|)}])/g).map(function(item) {
- if(!item)
- return null;
- var t = SIMPLE_TOKENS[item];
- if(t) {
- return {
- type: t
- };
- }
- if(item[0] === "[") {
- if(item[1] === "^" || item[1] === "!") {
- return {
- type: "inverted-char-set",
- value: item.substr(2, item.length - 3)
- };
- } else {
- return {
- type: "char-set",
- value: item.substr(1, item.length - 2)
- };
- }
- }
- return {
- type: "string",
- value: item
- };
- }).filter(Boolean).concat({
- type: "end"
- });
-}
-
-function createRoot() {
- var inOr = [];
- var process = createSeqment();
- var initial = true;
- return function(token) {
- switch(token.type) {
- case "or":
- inOr.push(initial);
- return "(";
- case "comma":
- if(inOr.length) {
- initial = inOr[inOr.length - 1];
- return "|";
- } else {
- return process({
- type: "string",
- value: ","
- }, initial);
- }
- case "closing-or":
- if(inOr.length === 0)
- throw new Error("Unmatched '}'");
- inOr.pop();
- return ")";
- case "end":
- if(inOr.length)
- throw new Error("Unmatched '{'");
- return process(token, initial);
- default:
- var result = process(token, initial);
- initial = false;
- return result;
- }
- };
-}
-
-function createSeqment() {
- var inSeqment = [];
- var process = createSimple();
- return function(token, initial) {
- switch(token.type) {
- case "one":
- case "one-many":
- case "zero-many":
- case "zero-one":
- inSeqment.push(token.type);
- return "(";
- case "segment-sep":
- if(inSeqment.length) {
- return "|";
- } else {
- return process({
- type: "string",
- value: "|"
- }, initial);
- }
- case "closing-segment":
- var segment = inSeqment.pop();
- switch(segment) {
- case "one":
- return ")";
- case "one-many":
- return ")+";
- case "zero-many":
- return ")*";
- case "zero-one":
- return ")?";
- }
- throw new Error("Unexcepted segment " + segment);
- case "end":
- if(inSeqment.length > 0) {
- throw new Error("Unmatched segment, missing ')'");
- }
- return process(token, initial);
- default:
- return process(token, initial);
- }
- };
-}
-
-function createSimple() {
- return function(token, initial) {
- switch(token.type) {
- case "path-sep":
- return "[\\\\/]+";
- case "any-path-segments":
- return "[\\\\/]+(?:(.+)[\\\\/]+)?";
- case "any-path":
- return "(.*)";
- case "any-path-segment":
- if(initial) {
- return "\\.[\\\\/]+(?:.*[\\\\/]+)?([^\\\\/]+)";
- } else {
- return "([^\\\\/]*)";
- }
- case "any-char":
- return "[^\\\\/]";
- case "inverted-char-set":
- return "[^" + token.value + "]";
- case "char-set":
- return "[" + token.value + "]";
- case "string":
- return token.value.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
- case "end":
- return "";
- default:
- throw new Error("Unsupported token '" + token.type + "'");
- }
- };
-}
-
-exports.globToRegExp = globToRegExp;
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/lib/node.js b/node_modules/webpack/node_modules/enhanced-resolve/lib/node.js deleted file mode 100644 index 1e79cdc25..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/lib/node.js +++ /dev/null @@ -1,144 +0,0 @@ -/*
- MIT License http://www.opensource.org/licenses/mit-license.php
- Author Tobias Koppers @sokra
-*/
-var ResolverFactory = require("./ResolverFactory");
-
-var NodeJsInputFileSystem = require("./NodeJsInputFileSystem");
-var CachedInputFileSystem = require("./CachedInputFileSystem");
-
-var nodeFileSystem = new CachedInputFileSystem(new NodeJsInputFileSystem(), 4000);
-
-var nodeContext = {
- environments: [
- "node+es3+es5+process+native"
- ]
-};
-
-var asyncResolver = ResolverFactory.createResolver({
- extensions: [".js", ".json", ".node"],
- fileSystem: nodeFileSystem
-});
-module.exports = function resolve(context, path, request, callback) {
- if(typeof context === "string") {
- callback = request;
- request = path;
- path = context;
- context = nodeContext;
- }
- asyncResolver.resolve(context, path, request, callback);
-};
-
-var syncResolver = ResolverFactory.createResolver({
- extensions: [".js", ".json", ".node"],
- useSyncFileSystemCalls: true,
- fileSystem: nodeFileSystem
-});
-module.exports.sync = function resolveSync(context, path, request) {
- if(typeof context === "string") {
- request = path;
- path = context;
- context = nodeContext;
- }
- return syncResolver.resolveSync(context, path, request);
-};
-
-var asyncContextResolver = ResolverFactory.createResolver({
- extensions: [".js", ".json", ".node"],
- resolveToContext: true,
- fileSystem: nodeFileSystem
-});
-module.exports.context = function resolveContext(context, path, request, callback) {
- if(typeof context === "string") {
- callback = request;
- request = path;
- path = context;
- context = nodeContext;
- }
- asyncContextResolver.resolve(context, path, request, callback);
-};
-
-var syncContextResolver = ResolverFactory.createResolver({
- extensions: [".js", ".json", ".node"],
- resolveToContext: true,
- useSyncFileSystemCalls: true,
- fileSystem: nodeFileSystem
-});
-module.exports.context.sync = function resolveContextSync(context, path, request) {
- if(typeof context === "string") {
- request = path;
- path = context;
- context = nodeContext;
- }
- return syncContextResolver.resolveSync(context, path, request);
-};
-
-var asyncLoaderResolver = ResolverFactory.createResolver({
- extensions: [".js", ".json", ".node"],
- moduleExtensions: ["-loader"],
- mainFields: ["loader", "main"],
- fileSystem: nodeFileSystem
-});
-module.exports.loader = function resolveLoader(context, path, request, callback) {
- if(typeof context === "string") {
- callback = request;
- request = path;
- path = context;
- context = nodeContext;
- }
- asyncLoaderResolver.resolve(context, path, request, callback);
-};
-
-var syncLoaderResolver = ResolverFactory.createResolver({
- extensions: [".js", ".json", ".node"],
- moduleExtensions: ["-loader"],
- mainFields: ["loader", "main"],
- useSyncFileSystemCalls: true,
- fileSystem: nodeFileSystem
-});
-module.exports.loader.sync = function resolveLoaderSync(context, path, request) {
- if(typeof context === "string") {
- request = path;
- path = context;
- context = nodeContext;
- }
- return syncLoaderResolver.resolveSync(context, path, request);
-};
-
-module.exports.create = function create(options) {
- options = Object.assign({
- fileSystem: nodeFileSystem
- }, options);
- var resolver = ResolverFactory.createResolver(options);
- return function(context, path, request, callback) {
- if(typeof context === "string") {
- callback = request;
- request = path;
- path = context;
- context = nodeContext;
- }
- resolver.resolve(context, path, request, callback);
- };
-};
-
-module.exports.create.sync = function createSync(options) {
- options = Object.assign({
- useSyncFileSystemCalls: true,
- fileSystem: nodeFileSystem
- }, options);
- var resolver = ResolverFactory.createResolver(options);
- return function(context, path, request) {
- if(typeof context === "string") {
- request = path;
- path = context;
- context = nodeContext;
- }
- return resolver.resolveSync(context, path, request);
- };
-};
-
-// Export Resolver, FileSystems and Plugins
-module.exports.ResolverFactory = ResolverFactory;
-
-module.exports.NodeJsInputFileSystem = NodeJsInputFileSystem;
-module.exports.CachedInputFileSystem = CachedInputFileSystem;
diff --git a/node_modules/webpack/node_modules/enhanced-resolve/package.json b/node_modules/webpack/node_modules/enhanced-resolve/package.json deleted file mode 100644 index 3d721fac0..000000000 --- a/node_modules/webpack/node_modules/enhanced-resolve/package.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "name": "enhanced-resolve", - "version": "3.4.1", - "author": "Tobias Koppers @sokra", - "description": "Offers a async require.resolve function. It's highly configurable.", - "files": [ - "lib" - ], - "dependencies": { - "graceful-fs": "^4.1.2", - "memory-fs": "^0.4.0", - "object-assign": "^4.0.1", - "tapable": "^0.2.7" - }, - "licenses": [ - { - "type": "MIT", - "url": "http://www.opensource.org/licenses/mit-license.php" - } - ], - "devDependencies": { - "beautify-lint": "^1.0.3", - "codecov.io": "^0.1.6", - "coveralls": "^2.11.6", - "eslint": "^3.14.1", - "eslint-plugin-node": "^3.0.5", - "eslint-plugin-nodeca": "^1.0.3", - "istanbul": "^0.4.1", - "js-beautify": "^1.5.10", - "mocha": "^2.3.4", - "should": "^8.0.2" - }, - "engines": { - "node": ">=4.3.0 <5.0.0 || >=5.10" - }, - "main": "lib/node.js", - "homepage": "http://github.com/webpack/enhanced-resolve", - "scripts": { - "beautify-lint": "beautify-lint lib/**.js test/*.js", - "beautify": "beautify-rewrite lib/**.js test/*.js", - "lint": "eslint lib test", - "pretest": "npm run lint && npm run beautify-lint", - "test": "mocha --full-trace --check-leaks", - "precover": "npm run lint && npm run beautify-lint", - "cover": "istanbul cover node_modules/mocha/bin/_mocha", - "travis": "npm run cover -- --report lcovonly" - }, - "repository": { - "type": "git", - "url": "git://github.com/webpack/enhanced-resolve.git" - } -} diff --git a/node_modules/webpack/node_modules/path-type/index.js b/node_modules/webpack/node_modules/path-type/index.js deleted file mode 100644 index 4ac9dd967..000000000 --- a/node_modules/webpack/node_modules/path-type/index.js +++ /dev/null @@ -1,26 +0,0 @@ -'use strict'; -const fs = require('fs'); -const pify = require('pify'); - -function type(fn, fn2, fp) { - if (typeof fp !== 'string') { - return Promise.reject(new TypeError(`Expected a string, got ${typeof fp}`)); - } - - return pify(fs[fn])(fp).then(stats => stats[fn2]()); -} - -function typeSync(fn, fn2, fp) { - if (typeof fp !== 'string') { - throw new TypeError(`Expected a string, got ${typeof fp}`); - } - - return fs[fn](fp)[fn2](); -} - -exports.file = type.bind(null, 'stat', 'isFile'); -exports.dir = type.bind(null, 'stat', 'isDirectory'); -exports.symlink = type.bind(null, 'lstat', 'isSymbolicLink'); -exports.fileSync = typeSync.bind(null, 'statSync', 'isFile'); -exports.dirSync = typeSync.bind(null, 'statSync', 'isDirectory'); -exports.symlinkSync = typeSync.bind(null, 'lstatSync', 'isSymbolicLink'); diff --git a/node_modules/webpack/node_modules/path-type/license b/node_modules/webpack/node_modules/path-type/license deleted file mode 100644 index 654d0bfe9..000000000 --- a/node_modules/webpack/node_modules/path-type/license +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) - -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. diff --git a/node_modules/webpack/node_modules/path-type/package.json b/node_modules/webpack/node_modules/path-type/package.json deleted file mode 100644 index 54336f352..000000000 --- a/node_modules/webpack/node_modules/path-type/package.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "name": "path-type", - "version": "2.0.0", - "description": "Check if a path is a file, directory, or symlink", - "license": "MIT", - "repository": "sindresorhus/path-type", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "engines": { - "node": ">=4" - }, - "scripts": { - "test": "xo && ava" - }, - "files": [ - "index.js" - ], - "keywords": [ - "path", - "fs", - "type", - "is", - "check", - "directory", - "dir", - "file", - "filepath", - "symlink", - "symbolic", - "link", - "stat", - "stats", - "filesystem" - ], - "dependencies": { - "pify": "^2.0.0" - }, - "devDependencies": { - "ava": "*", - "xo": "*" - }, - "xo": { - "esnext": true - } -} diff --git a/node_modules/webpack/node_modules/path-type/readme.md b/node_modules/webpack/node_modules/path-type/readme.md deleted file mode 100644 index b1ea61fe9..000000000 --- a/node_modules/webpack/node_modules/path-type/readme.md +++ /dev/null @@ -1,42 +0,0 @@ -# path-type [](https://travis-ci.org/sindresorhus/path-type) - -> Check if a path is a file, directory, or symlink - - -## Install - -``` -$ npm install --save path-type -``` - - -## Usage - -```js -const pathType = require('path-type'); - -pathType.file('package.json').then(isFile => { - console.log(isFile); - //=> true -}) -``` - - -## API - -### .file(path) -### .dir(path) -### .symlink(path) - -Returns a `Promise` for a `boolean` of whether the path is the checked type. - -### .fileSync(path) -### .dirSync(path) -### .symlinkSync(path) - -Returns a `boolean` of whether the path is the checked type. - - -## License - -MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/webpack/node_modules/read-pkg-up/index.js b/node_modules/webpack/node_modules/read-pkg-up/index.js deleted file mode 100644 index 26079760f..000000000 --- a/node_modules/webpack/node_modules/read-pkg-up/index.js +++ /dev/null @@ -1,26 +0,0 @@ -'use strict'; -const findUp = require('find-up'); -const readPkg = require('read-pkg'); - -module.exports = opts => { - return findUp('package.json', opts).then(fp => { - if (!fp) { - return {}; - } - - return readPkg(fp, opts).then(pkg => ({pkg, path: fp})); - }); -}; - -module.exports.sync = opts => { - const fp = findUp.sync('package.json', opts); - - if (!fp) { - return {}; - } - - return { - pkg: readPkg.sync(fp, opts), - path: fp - }; -}; diff --git a/node_modules/webpack/node_modules/read-pkg-up/license b/node_modules/webpack/node_modules/read-pkg-up/license deleted file mode 100644 index 654d0bfe9..000000000 --- a/node_modules/webpack/node_modules/read-pkg-up/license +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) - -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. diff --git a/node_modules/webpack/node_modules/read-pkg-up/package.json b/node_modules/webpack/node_modules/read-pkg-up/package.json deleted file mode 100644 index f09bf3c35..000000000 --- a/node_modules/webpack/node_modules/read-pkg-up/package.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "name": "read-pkg-up", - "version": "2.0.0", - "description": "Read the closest package.json file", - "license": "MIT", - "repository": "sindresorhus/read-pkg-up", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "engines": { - "node": ">=4" - }, - "scripts": { - "test": "xo && ava" - }, - "files": [ - "index.js" - ], - "keywords": [ - "json", - "read", - "parse", - "file", - "fs", - "graceful", - "load", - "pkg", - "package", - "find", - "up", - "find-up", - "findup", - "look-up", - "look", - "file", - "search", - "match", - "package", - "resolve", - "parent", - "parents", - "folder", - "directory", - "dir", - "walk", - "walking", - "path" - ], - "dependencies": { - "find-up": "^2.0.0", - "read-pkg": "^2.0.0" - }, - "devDependencies": { - "ava": "*", - "xo": "*" - }, - "xo": { - "esnext": true - } -} diff --git a/node_modules/webpack/node_modules/read-pkg-up/readme.md b/node_modules/webpack/node_modules/read-pkg-up/readme.md deleted file mode 100644 index ba18780f9..000000000 --- a/node_modules/webpack/node_modules/read-pkg-up/readme.md +++ /dev/null @@ -1,80 +0,0 @@ -# read-pkg-up [](https://travis-ci.org/sindresorhus/read-pkg-up) - -> Read the closest package.json file - - -## Why - -- [Finds the closest package.json](https://github.com/sindresorhus/find-up) -- [Gracefully handles filesystem issues](https://github.com/isaacs/node-graceful-fs) -- [Strips UTF-8 BOM](https://github.com/sindresorhus/strip-bom) -- [Throws more helpful JSON errors](https://github.com/sindresorhus/parse-json) -- [Normalizes the data](https://github.com/npm/normalize-package-data#what-normalization-currently-entails) - - -## Install - -``` -$ npm install --save read-pkg-up -``` - - -## Usage - -```js -const readPkgUp = require('read-pkg-up'); - -readPkgUp().then(result => { - console.log(result); - /* - { - pkg: { - name: 'awesome-package', - version: '1.0.0', - ... - }, - path: '/Users/sindresorhus/dev/awesome-package/package.json' - } - */ -}); -``` - - -## API - -### readPkgUp([options]) - -Returns a `Promise` for the result object. - -### readPkgUp.sync([options]) - -Returns the result object. - -#### options - -##### cwd - -Type: `string`<br> -Default: `.` - -Directory to start looking for a package.json file. - -##### normalize - -Type: `boolean`<br> -Default: `true` - -[Normalize](https://github.com/npm/normalize-package-data#what-normalization-currently-entails) the package data. - - -## Related - -- [read-pkg](https://github.com/sindresorhus/read-pkg) - Read a package.json file -- [pkg-up](https://github.com/sindresorhus/pkg-up) - Find the closest package.json file -- [find-up](https://github.com/sindresorhus/find-up) - Find a file by walking up parent directories -- [pkg-conf](https://github.com/sindresorhus/pkg-conf) - Get namespaced config from the closest package.json - - -## License - -MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/webpack/node_modules/read-pkg/index.js b/node_modules/webpack/node_modules/read-pkg/index.js deleted file mode 100644 index dff948b69..000000000 --- a/node_modules/webpack/node_modules/read-pkg/index.js +++ /dev/null @@ -1,47 +0,0 @@ -'use strict'; -const path = require('path'); -const loadJsonFile = require('load-json-file'); -const pathType = require('path-type'); - -module.exports = (fp, opts) => { - if (typeof fp !== 'string') { - opts = fp; - fp = '.'; - } - - opts = opts || {}; - - return pathType.dir(fp) - .then(isDir => { - if (isDir) { - fp = path.join(fp, 'package.json'); - } - - return loadJsonFile(fp); - }) - .then(x => { - if (opts.normalize !== false) { - require('normalize-package-data')(x); - } - - return x; - }); -}; - -module.exports.sync = (fp, opts) => { - if (typeof fp !== 'string') { - opts = fp; - fp = '.'; - } - - opts = opts || {}; - fp = pathType.dirSync(fp) ? path.join(fp, 'package.json') : fp; - - const x = loadJsonFile.sync(fp); - - if (opts.normalize !== false) { - require('normalize-package-data')(x); - } - - return x; -}; diff --git a/node_modules/webpack/node_modules/read-pkg/license b/node_modules/webpack/node_modules/read-pkg/license deleted file mode 100644 index 654d0bfe9..000000000 --- a/node_modules/webpack/node_modules/read-pkg/license +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) - -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. diff --git a/node_modules/webpack/node_modules/read-pkg/package.json b/node_modules/webpack/node_modules/read-pkg/package.json deleted file mode 100644 index b2322191f..000000000 --- a/node_modules/webpack/node_modules/read-pkg/package.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "name": "read-pkg", - "version": "2.0.0", - "description": "Read a package.json file", - "license": "MIT", - "repository": "sindresorhus/read-pkg", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "engines": { - "node": ">=4" - }, - "scripts": { - "test": "xo && ava" - }, - "files": [ - "index.js" - ], - "keywords": [ - "json", - "read", - "parse", - "file", - "fs", - "graceful", - "load", - "pkg", - "package", - "normalize" - ], - "dependencies": { - "load-json-file": "^2.0.0", - "normalize-package-data": "^2.3.2", - "path-type": "^2.0.0" - }, - "devDependencies": { - "ava": "*", - "xo": "*" - }, - "xo": { - "esnext": true - } -} diff --git a/node_modules/webpack/node_modules/read-pkg/readme.md b/node_modules/webpack/node_modules/read-pkg/readme.md deleted file mode 100644 index 5796008b8..000000000 --- a/node_modules/webpack/node_modules/read-pkg/readme.md +++ /dev/null @@ -1,79 +0,0 @@ -# read-pkg [](https://travis-ci.org/sindresorhus/read-pkg) - -> Read a package.json file - - -## Why - -- [Gracefully handles filesystem issues](https://github.com/isaacs/node-graceful-fs) -- [Strips UTF-8 BOM](https://github.com/sindresorhus/strip-bom) -- [Throws more helpful JSON errors](https://github.com/sindresorhus/parse-json) -- [Normalizes the data](https://github.com/npm/normalize-package-data#what-normalization-currently-entails) - - -## Install - -``` -$ npm install --save read-pkg -``` - - -## Usage - -```js -const readPkg = require('read-pkg'); - -readPkg().then(pkg => { - console.log(pkg); - //=> {name: 'read-pkg', ...} -}); - -readPkg(__dirname).then(pkg => { - console.log(pkg); - //=> {name: 'read-pkg', ...} -}); - -readPkg(path.join('unicorn', 'package.json')).then(pkg => { - console.log(pkg); - //=> {name: 'read-pkg', ...} -}); -``` - - -## API - -### readPkg([path], [options]) - -Returns a `Promise` for the parsed JSON. - -### readPkg.sync([path], [options]) - -Returns the parsed JSON. - -#### path - -Type: `string`<br> -Default: `.` - -Path to a `package.json` file or its directory. - -#### options - -##### normalize - -Type: `boolean`<br> -Default: `true` - -[Normalize](https://github.com/npm/normalize-package-data#what-normalization-currently-entails) the package data. - - -## Related - -- [read-pkg-up](https://github.com/sindresorhus/read-pkg-up) - Read the closest package.json file -- [write-pkg](https://github.com/sindresorhus/write-pkg) - Write a `package.json` file -- [load-json-file](https://github.com/sindresorhus/load-json-file) - Read and parse a JSON file - - -## License - -MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/webpack/node_modules/yargs-parser/CHANGELOG.md b/node_modules/webpack/node_modules/yargs-parser/CHANGELOG.md deleted file mode 100644 index 3ad3df821..000000000 --- a/node_modules/webpack/node_modules/yargs-parser/CHANGELOG.md +++ /dev/null @@ -1,223 +0,0 @@ -# Change Log - -All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. - -<a name="7.0.0"></a> -# [7.0.0](https://github.com/yargs/yargs-parser/compare/v6.0.1...v7.0.0) (2017-05-02) - - -### Chores - -* revert populate-- logic ([#91](https://github.com/yargs/yargs-parser/issues/91)) ([6003e6d](https://github.com/yargs/yargs-parser/commit/6003e6d)) - - -### BREAKING CHANGES - -* populate-- now defaults to false. - - - -<a name="6.0.1"></a> -## [6.0.1](https://github.com/yargs/yargs-parser/compare/v6.0.0...v6.0.1) (2017-05-01) - - -### Bug Fixes - -* default '--' to undefined when not provided; this is closer to the array API ([#90](https://github.com/yargs/yargs-parser/issues/90)) ([4e739cc](https://github.com/yargs/yargs-parser/commit/4e739cc)) - - - -<a name="6.0.0"></a> -# [6.0.0](https://github.com/yargs/yargs-parser/compare/v4.2.1...v6.0.0) (2017-05-01) - - -### Bug Fixes - -* environment variables should take precedence over config file ([#81](https://github.com/yargs/yargs-parser/issues/81)) ([76cee1f](https://github.com/yargs/yargs-parser/commit/76cee1f)) -* parsing hints should apply for dot notation keys ([#86](https://github.com/yargs/yargs-parser/issues/86)) ([3e47d62](https://github.com/yargs/yargs-parser/commit/3e47d62)) - - -### Chores - -* upgrade to newest version of camelcase ([#87](https://github.com/yargs/yargs-parser/issues/87)) ([f1903aa](https://github.com/yargs/yargs-parser/commit/f1903aa)) - - -### Features - -* add -- option which allows arguments after the -- flag to be returned separated from positional arguments ([#84](https://github.com/yargs/yargs-parser/issues/84)) ([2572ca8](https://github.com/yargs/yargs-parser/commit/2572ca8)) -* when parsing stops, we now populate "--" by default ([#88](https://github.com/yargs/yargs-parser/issues/88)) ([cd666db](https://github.com/yargs/yargs-parser/commit/cd666db)) - - -### BREAKING CHANGES - -* rather than placing arguments in "_", when parsing is stopped via "--"; we now populate an array called "--" by default. -* camelcase now requires Node 4+. -* environment variables will now override config files (args, env, config-file, config-object) - - - -<a name="5.0.0"></a> -# [5.0.0](https://github.com/yargs/yargs-parser/compare/v4.2.1...v5.0.0) (2017-02-18) - - -### Bug Fixes - -* environment variables should take precedence over config file ([#81](https://github.com/yargs/yargs-parser/issues/81)) ([76cee1f](https://github.com/yargs/yargs-parser/commit/76cee1f)) - - -### BREAKING CHANGES - -* environment variables will now override config files (args, env, config-file, config-object) - - - -<a name="4.2.1"></a> -## [4.2.1](https://github.com/yargs/yargs-parser/compare/v4.2.0...v4.2.1) (2017-01-02) - - -### Bug Fixes - -* flatten/duplicate regression ([#75](https://github.com/yargs/yargs-parser/issues/75)) ([68d68a0](https://github.com/yargs/yargs-parser/commit/68d68a0)) - - - -<a name="4.2.0"></a> -# [4.2.0](https://github.com/yargs/yargs-parser/compare/v4.1.0...v4.2.0) (2016-12-01) - - -### Bug Fixes - -* inner objects in configs had their keys appended to top-level key when dot-notation was disabled ([#72](https://github.com/yargs/yargs-parser/issues/72)) ([0b1b5f9](https://github.com/yargs/yargs-parser/commit/0b1b5f9)) - - -### Features - -* allow multiple arrays to be provided, rather than always combining ([#71](https://github.com/yargs/yargs-parser/issues/71)) ([0f0fb2d](https://github.com/yargs/yargs-parser/commit/0f0fb2d)) - - - -<a name="4.1.0"></a> -# [4.1.0](https://github.com/yargs/yargs-parser/compare/v4.0.2...v4.1.0) (2016-11-07) - - -### Features - -* apply coercions to default options ([#65](https://github.com/yargs/yargs-parser/issues/65)) ([c79052b](https://github.com/yargs/yargs-parser/commit/c79052b)) -* handle dot notation boolean options ([#63](https://github.com/yargs/yargs-parser/issues/63)) ([02c3545](https://github.com/yargs/yargs-parser/commit/02c3545)) - - - -<a name="4.0.2"></a> -## [4.0.2](https://github.com/yargs/yargs-parser/compare/v4.0.1...v4.0.2) (2016-09-30) - - -### Bug Fixes - -* whoops, let's make the assign not change the Object key order ([29d069a](https://github.com/yargs/yargs-parser/commit/29d069a)) - - - -<a name="4.0.1"></a> -## [4.0.1](https://github.com/yargs/yargs-parser/compare/v4.0.0...v4.0.1) (2016-09-30) - - -### Bug Fixes - -* lodash.assign was deprecated ([#59](https://github.com/yargs/yargs-parser/issues/59)) ([5e7eb11](https://github.com/yargs/yargs-parser/commit/5e7eb11)) - - - -<a name="4.0.0"></a> -# [4.0.0](https://github.com/yargs/yargs-parser/compare/v3.2.0...v4.0.0) (2016-09-26) - - -### Bug Fixes - -* coerce should be applied to the final objects and arrays created ([#57](https://github.com/yargs/yargs-parser/issues/57)) ([4ca69da](https://github.com/yargs/yargs-parser/commit/4ca69da)) - - -### BREAKING CHANGES - -* coerce is no longer applied to individual arguments in an implicit array. - - - -<a name="3.2.0"></a> -# [3.2.0](https://github.com/yargs/yargs-parser/compare/v3.1.0...v3.2.0) (2016-08-13) - - -### Features - -* coerce full array instead of each element ([#51](https://github.com/yargs/yargs-parser/issues/51)) ([cc4dc56](https://github.com/yargs/yargs-parser/commit/cc4dc56)) - - - -<a name="3.1.0"></a> -# [3.1.0](https://github.com/yargs/yargs-parser/compare/v3.0.0...v3.1.0) (2016-08-09) - - -### Bug Fixes - -* address pkgConf parsing bug outlined in [#37](https://github.com/yargs/yargs-parser/issues/37) ([#45](https://github.com/yargs/yargs-parser/issues/45)) ([be76ee6](https://github.com/yargs/yargs-parser/commit/be76ee6)) -* better parsing of negative values ([#44](https://github.com/yargs/yargs-parser/issues/44)) ([2e43692](https://github.com/yargs/yargs-parser/commit/2e43692)) -* check aliases when guessing defaults for arguments fixes [#41](https://github.com/yargs/yargs-parser/issues/41) ([#43](https://github.com/yargs/yargs-parser/issues/43)) ([f3e4616](https://github.com/yargs/yargs-parser/commit/f3e4616)) - - -### Features - -* added coerce option, for providing specialized argument parsing ([#42](https://github.com/yargs/yargs-parser/issues/42)) ([7b49cd2](https://github.com/yargs/yargs-parser/commit/7b49cd2)) - - - -<a name="3.0.0"></a> -# [3.0.0](https://github.com/yargs/yargs-parser/compare/v2.4.1...v3.0.0) (2016-08-07) - - -### Bug Fixes - -* parsing issue with numeric character in group of options ([#19](https://github.com/yargs/yargs-parser/issues/19)) ([f743236](https://github.com/yargs/yargs-parser/commit/f743236)) -* upgraded lodash.assign ([5d7fdf4](https://github.com/yargs/yargs-parser/commit/5d7fdf4)) - -### BREAKING CHANGES - -* subtle change to how values are parsed in a group of single-character arguments. -* _first released in 3.1.0, better handling of negative values should be considered a breaking change._ - - - -<a name="2.4.1"></a> -## [2.4.1](https://github.com/yargs/yargs-parser/compare/v2.4.0...v2.4.1) (2016-07-16) - - -### Bug Fixes - -* **count:** do not increment a default value ([#39](https://github.com/yargs/yargs-parser/issues/39)) ([b04a189](https://github.com/yargs/yargs-parser/commit/b04a189)) - - - -<a name="2.4.0"></a> -# [2.4.0](https://github.com/yargs/yargs-parser/compare/v2.3.0...v2.4.0) (2016-04-11) - - -### Features - -* **environment:** Support nested options in environment variables ([#26](https://github.com/yargs/yargs-parser/issues/26)) thanks [@elas7](https://github.com/elas7) \o/ ([020778b](https://github.com/yargs/yargs-parser/commit/020778b)) - - - -<a name="2.3.0"></a> -# [2.3.0](https://github.com/yargs/yargs-parser/compare/v2.2.0...v2.3.0) (2016-04-09) - - -### Bug Fixes - -* **boolean:** fix for boolean options with non boolean defaults (#20) ([2dbe86b](https://github.com/yargs/yargs-parser/commit/2dbe86b)), closes [(#20](https://github.com/(/issues/20) -* **package:** remove tests from tarball ([0353c0d](https://github.com/yargs/yargs-parser/commit/0353c0d)) -* **parsing:** handle calling short option with an empty string as the next value. ([a867165](https://github.com/yargs/yargs-parser/commit/a867165)) -* boolean flag when next value contains the strings 'true' or 'false'. ([69941a6](https://github.com/yargs/yargs-parser/commit/69941a6)) -* update dependencies; add standard-version bin for next release (#24) ([822d9d5](https://github.com/yargs/yargs-parser/commit/822d9d5)) - -### Features - -* **configuration:** Allow to pass configuration objects to yargs-parser ([0780900](https://github.com/yargs/yargs-parser/commit/0780900)) -* **normalize:** allow normalize to work with arrays ([e0eaa1a](https://github.com/yargs/yargs-parser/commit/e0eaa1a)) diff --git a/node_modules/webpack/node_modules/yargs-parser/LICENSE.txt b/node_modules/webpack/node_modules/yargs-parser/LICENSE.txt deleted file mode 100644 index 836440bef..000000000 --- a/node_modules/webpack/node_modules/yargs-parser/LICENSE.txt +++ /dev/null @@ -1,14 +0,0 @@ -Copyright (c) 2016, Contributors - -Permission to use, copy, modify, and/or distribute this software -for any purpose with or without fee is hereby granted, provided -that the above copyright notice and this permission notice -appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES -OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE -LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES -OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, -WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, -ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/webpack/node_modules/yargs-parser/README.md b/node_modules/webpack/node_modules/yargs-parser/README.md deleted file mode 100644 index d1817fccc..000000000 --- a/node_modules/webpack/node_modules/yargs-parser/README.md +++ /dev/null @@ -1,281 +0,0 @@ -# yargs-parser - -[](https://travis-ci.org/yargs/yargs-parser) -[](https://coveralls.io/r/yargs/yargs-parser?branch=master) -[](https://www.npmjs.com/package/yargs-parser) -[](https://ci.appveyor.com/project/bcoe/yargs-parser) -[](https://github.com/conventional-changelog/standard-version) - - -The mighty option parser used by [yargs](https://github.com/yargs/yargs). - -visit the [yargs website](http://yargs.js.org/) for more examples, and thorough usage instructions. - -<img width="250" src="https://raw.githubusercontent.com/yargs/yargs-parser/master/yargs-logo.png"> - -## Example - -```sh -npm i yargs-parser --save -``` - -```js -var argv = require('yargs-parser')(process.argv.slice(2)) -console.log(argv) -``` - -```sh -node example.js --foo=33 --bar hello -{ _: [], foo: 33, bar: 'hello' } -``` - -_or parse a string!_ - -```js -var argv = require('./')('--foo=99 --bar=33') -console.log(argv) -``` - -```sh -{ _: [], foo: 99, bar: 33 } -``` - -Convert an array of mixed types before passing to `yargs-parser`: - -```js -var parse = require('yargs-parser') -parse(['-f', 11, '--zoom', 55].join(' ')) // <-- array to string -parse(['-f', 11, '--zoom', 55].map(String)) // <-- array of strings -``` - -## API - -### require('yargs-parser')(args, opts={}) - -Parses command line arguments returning a simple mapping of keys and values. - -**expects:** - -* `args`: a string or array of strings representing the options to parse. -* `opts`: provide a set of hints indicating how `args` should be parsed: - * `opts.alias`: an object representing the set of aliases for a key: `{alias: {foo: ['f']}}`. - * `opts.array`: indicate that keys should be parsed as an array: `{array: ['foo', 'bar']}`. - * `opts.boolean`: arguments should be parsed as booleans: `{boolean: ['x', 'y']}`. - * `opts.config`: indicate a key that represents a path to a configuration file (this file will be loaded and parsed). - * `opts.coerce`: provide a custom synchronous function that returns a coerced value from the argument provided - (or throws an error), e.g. `{coerce: {foo: function (arg) {return modifiedArg}}}`. - * `opts.count`: indicate a key that should be used as a counter, e.g., `-vvv` = `{v: 3}`. - * `opts.default`: provide default values for keys: `{default: {x: 33, y: 'hello world!'}}`. - * `opts.envPrefix`: environment variables (`process.env`) with the prefix provided should be parsed. - * `opts.narg`: specify that a key requires `n` arguments: `{narg: {x: 2}}`. - * `opts.normalize`: `path.normalize()` will be applied to values set to this key. - * `opts.string`: keys should be treated as strings (even if they resemble a number `-x 33`). - * `opts.configuration`: provide configuration options to the yargs-parser (see: [configuration](#configuration)). - * `opts.number`: keys should be treated as numbers. - * `opts['--']`: arguments after the end-of-options flag `--` will be set to the `argv.['--']` array instead of being set to the `argv._` array. - -**returns:** - -* `obj`: an object representing the parsed value of `args` - * `key/value`: key value pairs for each argument and their aliases. - * `_`: an array representing the positional arguments. - * [optional] `--`: an array with arguments after the end-of-options flag `--`. - -### require('yargs-parser').detailed(args, opts={}) - -Parses a command line string, returning detailed information required by the -yargs engine. - -**expects:** - -* `args`: a string or array of strings representing options to parse. -* `opts`: provide a set of hints indicating how `args`, inputs are identical to `require('yargs-parser')(args, opts={})`. - -**returns:** - -* `argv`: an object representing the parsed value of `args` - * `key/value`: key value pairs for each argument and their aliases. - * `_`: an array representing the positional arguments. -* `error`: populated with an error object if an exception occurred during parsing. -* `aliases`: the inferred list of aliases built by combining lists in `opts.alias`. -* `newAliases`: any new aliases added via camel-case expansion. -* `configuration`: the configuration loaded from the `yargs` stanza in package.json. - -<a name="configuration"></a> - -### Configuration - -The yargs-parser applies several automated transformations on the keys provided -in `args`. These features can be turned on and off using the `configuration` field -of `opts`. - -```js -var parsed = parser(['--no-dice'], { - configuration: { - 'boolean-negation': false - } -}) -``` - -### short option groups - -* default: `true`. -* key: `short-option-groups`. - -Should a group of short-options be treated as boolean flags? - -```sh -node example.js -abc -{ _: [], a: true, b: true, c: true } -``` - -_if disabled:_ - -```sh -node example.js -abc -{ _: [], abc: true } -``` - -### camel-case expansion - -* default: `true`. -* key: `camel-case-expansion`. - -Should hyphenated arguments be expanded into camel-case aliases? - -```sh -node example.js --foo-bar -{ _: [], 'foo-bar': true, fooBar: true } -``` - -_if disabled:_ - -```sh -node example.js --foo-bar -{ _: [], 'foo-bar': true } -``` - -### dot-notation - -* default: `true` -* key: `dot-notation` - -Should keys that contain `.` be treated as objects? - -```sh -node example.js --foo.bar -{ _: [], foo: { bar: true } } -``` - -_if disabled:_ - -```sh -node example.js --foo.bar -{ _: [], "foo.bar": true } -``` - -### parse numbers - -* default: `true` -* key: `parse-numbers` - -Should keys that look like numbers be treated as such? - -```sh -node example.js --foo=99.3 -{ _: [], foo: 99.3 } -``` - -_if disabled:_ - -```sh -node example.js --foo=99.3 -{ _: [], foo: "99.3" } -``` - -### boolean negation - -* default: `true` -* key: `boolean-negation` - -Should variables prefixed with `--no` be treated as negations? - -```sh -node example.js --no-foo -{ _: [], foo: false } -``` - -_if disabled:_ - -```sh -node example.js --no-foo -{ _: [], "no-foo": true } -``` - -### duplicate arguments array - -* default: `true` -* key: `duplicate-arguments-array` - -Should arguments be coerced into an array when duplicated: - -```sh -node example.js -x 1 -x 2 -{ _: [], x: [1, 2] } -``` - -_if disabled:_ - -```sh -node example.js -x 1 -x 2 -{ _: [], x: 2 } -``` - -### flatten duplicate arrays - -* default: `true` -* key: `flatten-duplicate-arrays` - -Should array arguments be coerced into a single array when duplicated: - -```sh -node example.js -x 1 2 -x 3 4 -{ _: [], x: [1, 2, 3, 4] } -``` - -_if disabled:_ - -```sh -node example.js -x 1 2 -x 3 4 -{ _: [], x: [[1, 2], [3, 4]] } -``` - -### populate -- - -* default: `false`. -* key: `populate--` - -Should unparsed flags be stored in `--` or `_`. - -_If disabled:_ - -```sh -node example.js a -b -- x y -{ _: [ 'a', 'x', 'y' ], b: true } -``` - -_If enabled:_ - -```sh -node example.js a -b -- x y -{ _: [ 'a' ], '--': [ 'x', 'y' ], b: true } -``` - -## Special Thanks - -The yargs project evolves from optimist and minimist. It owes its -existence to a lot of James Halliday's hard work. Thanks [substack](https://github.com/substack) **beep** **boop** \o/ - -## License - -ISC diff --git a/node_modules/webpack/node_modules/yargs-parser/index.js b/node_modules/webpack/node_modules/yargs-parser/index.js deleted file mode 100644 index 73154066f..000000000 --- a/node_modules/webpack/node_modules/yargs-parser/index.js +++ /dev/null @@ -1,764 +0,0 @@ -var camelCase = require('camelcase') -var path = require('path') -var tokenizeArgString = require('./lib/tokenize-arg-string') -var util = require('util') - -function parse (args, opts) { - if (!opts) opts = {} - // allow a string argument to be passed in rather - // than an argv array. - args = tokenizeArgString(args) - // aliases might have transitive relationships, normalize this. - var aliases = combineAliases(opts.alias || {}) - var configuration = assign({ - 'short-option-groups': true, - 'camel-case-expansion': true, - 'dot-notation': true, - 'parse-numbers': true, - 'boolean-negation': true, - 'duplicate-arguments-array': true, - 'flatten-duplicate-arrays': true, - 'populate--': false - }, opts.configuration) - var defaults = opts.default || {} - var configObjects = opts.configObjects || [] - var envPrefix = opts.envPrefix - var notFlagsOption = configuration['populate--'] - var notFlagsArgv = notFlagsOption ? '--' : '_' - var newAliases = {} - // allow a i18n handler to be passed in, default to a fake one (util.format). - var __ = opts.__ || function (str) { - return util.format.apply(util, Array.prototype.slice.call(arguments)) - } - var error = null - var flags = { - aliases: {}, - arrays: {}, - bools: {}, - strings: {}, - numbers: {}, - counts: {}, - normalize: {}, - configs: {}, - defaulted: {}, - nargs: {}, - coercions: {} - } - var negative = /^-[0-9]+(\.[0-9]+)?/ - - ;[].concat(opts.array).filter(Boolean).forEach(function (key) { - flags.arrays[key] = true - }) - - ;[].concat(opts.boolean).filter(Boolean).forEach(function (key) { - flags.bools[key] = true - }) - - ;[].concat(opts.string).filter(Boolean).forEach(function (key) { - flags.strings[key] = true - }) - - ;[].concat(opts.number).filter(Boolean).forEach(function (key) { - flags.numbers[key] = true - }) - - ;[].concat(opts.count).filter(Boolean).forEach(function (key) { - flags.counts[key] = true - }) - - ;[].concat(opts.normalize).filter(Boolean).forEach(function (key) { - flags.normalize[key] = true - }) - - Object.keys(opts.narg || {}).forEach(function (k) { - flags.nargs[k] = opts.narg[k] - }) - - Object.keys(opts.coerce || {}).forEach(function (k) { - flags.coercions[k] = opts.coerce[k] - }) - - if (Array.isArray(opts.config) || typeof opts.config === 'string') { - ;[].concat(opts.config).filter(Boolean).forEach(function (key) { - flags.configs[key] = true - }) - } else { - Object.keys(opts.config || {}).forEach(function (k) { - flags.configs[k] = opts.config[k] - }) - } - - // create a lookup table that takes into account all - // combinations of aliases: {f: ['foo'], foo: ['f']} - extendAliases(opts.key, aliases, opts.default, flags.arrays) - - // apply default values to all aliases. - Object.keys(defaults).forEach(function (key) { - (flags.aliases[key] || []).forEach(function (alias) { - defaults[alias] = defaults[key] - }) - }) - - var argv = { _: [] } - - Object.keys(flags.bools).forEach(function (key) { - setArg(key, !(key in defaults) ? false : defaults[key]) - setDefaulted(key) - }) - - var notFlags = [] - if (args.indexOf('--') !== -1) { - notFlags = args.slice(args.indexOf('--') + 1) - args = args.slice(0, args.indexOf('--')) - } - - for (var i = 0; i < args.length; i++) { - var arg = args[i] - var broken - var key - var letters - var m - var next - var value - - // -- seperated by = - if (arg.match(/^--.+=/) || ( - !configuration['short-option-groups'] && arg.match(/^-.+=/) - )) { - // Using [\s\S] instead of . because js doesn't support the - // 'dotall' regex modifier. See: - // http://stackoverflow.com/a/1068308/13216 - m = arg.match(/^--?([^=]+)=([\s\S]*)$/) - - // nargs format = '--f=monkey washing cat' - if (checkAllAliases(m[1], flags.nargs)) { - args.splice(i + 1, 0, m[2]) - i = eatNargs(i, m[1], args) - // arrays format = '--f=a b c' - } else if (checkAllAliases(m[1], flags.arrays) && args.length > i + 1) { - args.splice(i + 1, 0, m[2]) - i = eatArray(i, m[1], args) - } else { - setArg(m[1], m[2]) - } - } else if (arg.match(/^--no-.+/) && configuration['boolean-negation']) { - key = arg.match(/^--no-(.+)/)[1] - setArg(key, false) - - // -- seperated by space. - } else if (arg.match(/^--.+/) || ( - !configuration['short-option-groups'] && arg.match(/^-.+/) - )) { - key = arg.match(/^--?(.+)/)[1] - - // nargs format = '--foo a b c' - if (checkAllAliases(key, flags.nargs)) { - i = eatNargs(i, key, args) - // array format = '--foo a b c' - } else if (checkAllAliases(key, flags.arrays) && args.length > i + 1) { - i = eatArray(i, key, args) - } else { - next = args[i + 1] - - if (next !== undefined && (!next.match(/^-/) || - next.match(negative)) && - !checkAllAliases(key, flags.bools) && - !checkAllAliases(key, flags.counts)) { - setArg(key, next) - i++ - } else if (/^(true|false)$/.test(next)) { - setArg(key, next) - i++ - } else { - setArg(key, defaultForType(guessType(key, flags))) - } - } - - // dot-notation flag seperated by '='. - } else if (arg.match(/^-.\..+=/)) { - m = arg.match(/^-([^=]+)=([\s\S]*)$/) - setArg(m[1], m[2]) - - // dot-notation flag seperated by space. - } else if (arg.match(/^-.\..+/)) { - next = args[i + 1] - key = arg.match(/^-(.\..+)/)[1] - - if (next !== undefined && !next.match(/^-/) && - !checkAllAliases(key, flags.bools) && - !checkAllAliases(key, flags.counts)) { - setArg(key, next) - i++ - } else { - setArg(key, defaultForType(guessType(key, flags))) - } - } else if (arg.match(/^-[^-]+/) && !arg.match(negative)) { - letters = arg.slice(1, -1).split('') - broken = false - - for (var j = 0; j < letters.length; j++) { - next = arg.slice(j + 2) - - if (letters[j + 1] && letters[j + 1] === '=') { - value = arg.slice(j + 3) - key = letters[j] - - // nargs format = '-f=monkey washing cat' - if (checkAllAliases(key, flags.nargs)) { - args.splice(i + 1, 0, value) - i = eatNargs(i, key, args) - // array format = '-f=a b c' - } else if (checkAllAliases(key, flags.arrays) && args.length > i + 1) { - args.splice(i + 1, 0, value) - i = eatArray(i, key, args) - } else { - setArg(key, value) - } - - broken = true - break - } - - if (next === '-') { - setArg(letters[j], next) - continue - } - - // current letter is an alphabetic character and next value is a number - if (/[A-Za-z]/.test(letters[j]) && - /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) { - setArg(letters[j], next) - broken = true - break - } - - if (letters[j + 1] && letters[j + 1].match(/\W/)) { - setArg(letters[j], next) - broken = true - break - } else { - setArg(letters[j], defaultForType(guessType(letters[j], flags))) - } - } - - key = arg.slice(-1)[0] - - if (!broken && key !== '-') { - // nargs format = '-f a b c' - if (checkAllAliases(key, flags.nargs)) { - i = eatNargs(i, key, args) - // array format = '-f a b c' - } else if (checkAllAliases(key, flags.arrays) && args.length > i + 1) { - i = eatArray(i, key, args) - } else { - next = args[i + 1] - - if (next !== undefined && (!/^(-|--)[^-]/.test(next) || - next.match(negative)) && - !checkAllAliases(key, flags.bools) && - !checkAllAliases(key, flags.counts)) { - setArg(key, next) - i++ - } else if (/^(true|false)$/.test(next)) { - setArg(key, next) - i++ - } else { - setArg(key, defaultForType(guessType(key, flags))) - } - } - } - } else { - argv._.push( - flags.strings['_'] || !isNumber(arg) ? arg : Number(arg) - ) - } - } - - // order of precedence: - // 1. command line arg - // 2. value from env var - // 3. value from config file - // 4. value from config objects - // 5. configured default value - applyEnvVars(argv, true) // special case: check env vars that point to config file - applyEnvVars(argv, false) - setConfig(argv) - setConfigObjects() - applyDefaultsAndAliases(argv, flags.aliases, defaults) - applyCoercions(argv) - - // for any counts either not in args or without an explicit default, set to 0 - Object.keys(flags.counts).forEach(function (key) { - if (!hasKey(argv, key.split('.'))) setArg(key, 0) - }) - - // '--' defaults to undefined. - if (notFlagsOption && notFlags.length) argv[notFlagsArgv] = [] - notFlags.forEach(function (key) { - argv[notFlagsArgv].push(key) - }) - - // how many arguments should we consume, based - // on the nargs option? - function eatNargs (i, key, args) { - var toEat = checkAllAliases(key, flags.nargs) - - if (args.length - (i + 1) < toEat) error = Error(__('Not enough arguments following: %s', key)) - - for (var ii = i + 1; ii < (toEat + i + 1); ii++) { - setArg(key, args[ii]) - } - - return (i + toEat) - } - - // if an option is an array, eat all non-hyphenated arguments - // following it... YUM! - // e.g., --foo apple banana cat becomes ["apple", "banana", "cat"] - function eatArray (i, key, args) { - var start = i + 1 - var argsToSet = [] - var multipleArrayFlag = i > 0 - for (var ii = i + 1; ii < args.length; ii++) { - if (/^-/.test(args[ii]) && !negative.test(args[ii])) { - if (ii === start) { - setArg(key, defaultForType('array')) - } - multipleArrayFlag = true - break - } - i = ii - argsToSet.push(args[ii]) - } - if (multipleArrayFlag) { - setArg(key, argsToSet.map(function (arg) { - return processValue(key, arg) - })) - } else { - argsToSet.forEach(function (arg) { - setArg(key, arg) - }) - } - - return i - } - - function setArg (key, val) { - unsetDefaulted(key) - - if (/-/.test(key) && !(flags.aliases[key] && flags.aliases[key].length) && configuration['camel-case-expansion']) { - var c = camelCase(key) - flags.aliases[key] = [c] - newAliases[c] = true - } - - var value = processValue(key, val) - - var splitKey = key.split('.') - setKey(argv, splitKey, value) - - // handle populating aliases of the full key - if (flags.aliases[key]) { - flags.aliases[key].forEach(function (x) { - x = x.split('.') - setKey(argv, x, value) - }) - } - - // handle populating aliases of the first element of the dot-notation key - if (splitKey.length > 1 && configuration['dot-notation']) { - ;(flags.aliases[splitKey[0]] || []).forEach(function (x) { - x = x.split('.') - - // expand alias with nested objects in key - var a = [].concat(splitKey) - a.shift() // nuke the old key. - x = x.concat(a) - - setKey(argv, x, value) - }) - } - - // Set normalize getter and setter when key is in 'normalize' but isn't an array - if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) { - var keys = [key].concat(flags.aliases[key] || []) - keys.forEach(function (key) { - argv.__defineSetter__(key, function (v) { - val = path.normalize(v) - }) - - argv.__defineGetter__(key, function () { - return typeof val === 'string' ? path.normalize(val) : val - }) - }) - } - } - - function processValue (key, val) { - // handle parsing boolean arguments --foo=true --bar false. - if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) { - if (typeof val === 'string') val = val === 'true' - } - - var value = val - if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.coercions)) { - if (isNumber(val)) value = Number(val) - if (!isUndefined(val) && !isNumber(val) && checkAllAliases(key, flags.numbers)) value = NaN - } - - // increment a count given as arg (either no value or value parsed as boolean) - if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === 'boolean')) { - value = increment - } - - // Set normalized value when key is in 'normalize' and in 'arrays' - if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) { - if (Array.isArray(val)) value = val.map(path.normalize) - else value = path.normalize(val) - } - return value - } - - // set args from config.json file, this should be - // applied last so that defaults can be applied. - function setConfig (argv) { - var configLookup = {} - - // expand defaults/aliases, in-case any happen to reference - // the config.json file. - applyDefaultsAndAliases(configLookup, flags.aliases, defaults) - - Object.keys(flags.configs).forEach(function (configKey) { - var configPath = argv[configKey] || configLookup[configKey] - if (configPath) { - try { - var config = null - var resolvedConfigPath = path.resolve(process.cwd(), configPath) - - if (typeof flags.configs[configKey] === 'function') { - try { - config = flags.configs[configKey](resolvedConfigPath) - } catch (e) { - config = e - } - if (config instanceof Error) { - error = config - return - } - } else { - config = require(resolvedConfigPath) - } - - setConfigObject(config) - } catch (ex) { - if (argv[configKey]) error = Error(__('Invalid JSON config file: %s', configPath)) - } - } - }) - } - - // set args from config object. - // it recursively checks nested objects. - function setConfigObject (config, prev) { - Object.keys(config).forEach(function (key) { - var value = config[key] - var fullKey = prev ? prev + '.' + key : key - - // if the value is an inner object and we have dot-notation - // enabled, treat inner objects in config the same as - // heavily nested dot notations (foo.bar.apple). - if (typeof value === 'object' && !Array.isArray(value) && configuration['dot-notation']) { - // if the value is an object but not an array, check nested object - setConfigObject(value, fullKey) - } else { - // setting arguments via CLI takes precedence over - // values within the config file. - if (!hasKey(argv, fullKey.split('.')) || (flags.defaulted[fullKey])) { - setArg(fullKey, value) - } - } - }) - } - - // set all config objects passed in opts - function setConfigObjects () { - if (typeof configObjects === 'undefined') return - configObjects.forEach(function (configObject) { - setConfigObject(configObject) - }) - } - - function applyEnvVars (argv, configOnly) { - if (typeof envPrefix === 'undefined') return - - var prefix = typeof envPrefix === 'string' ? envPrefix : '' - Object.keys(process.env).forEach(function (envVar) { - if (prefix === '' || envVar.lastIndexOf(prefix, 0) === 0) { - // get array of nested keys and convert them to camel case - var keys = envVar.split('__').map(function (key, i) { - if (i === 0) { - key = key.substring(prefix.length) - } - return camelCase(key) - }) - - if (((configOnly && flags.configs[keys.join('.')]) || !configOnly) && (!hasKey(argv, keys) || flags.defaulted[keys.join('.')])) { - setArg(keys.join('.'), process.env[envVar]) - } - } - }) - } - - function applyCoercions (argv) { - var coerce - Object.keys(argv).forEach(function (key) { - coerce = checkAllAliases(key, flags.coercions) - if (typeof coerce === 'function') { - try { - argv[key] = coerce(argv[key]) - } catch (err) { - error = err - } - } - }) - } - - function applyDefaultsAndAliases (obj, aliases, defaults) { - Object.keys(defaults).forEach(function (key) { - if (!hasKey(obj, key.split('.'))) { - setKey(obj, key.split('.'), defaults[key]) - - ;(aliases[key] || []).forEach(function (x) { - if (hasKey(obj, x.split('.'))) return - setKey(obj, x.split('.'), defaults[key]) - }) - } - }) - } - - function hasKey (obj, keys) { - var o = obj - - if (!configuration['dot-notation']) keys = [keys.join('.')] - - keys.slice(0, -1).forEach(function (key) { - o = (o[key] || {}) - }) - - var key = keys[keys.length - 1] - - if (typeof o !== 'object') return false - else return key in o - } - - function setKey (obj, keys, value) { - var o = obj - - if (!configuration['dot-notation']) keys = [keys.join('.')] - - keys.slice(0, -1).forEach(function (key) { - if (o[key] === undefined) o[key] = {} - o = o[key] - }) - - var key = keys[keys.length - 1] - - var isTypeArray = checkAllAliases(keys.join('.'), flags.arrays) - var isValueArray = Array.isArray(value) - var duplicate = configuration['duplicate-arguments-array'] - - if (value === increment) { - o[key] = increment(o[key]) - } else if (Array.isArray(o[key])) { - if (duplicate && isTypeArray && isValueArray) { - o[key] = configuration['flatten-duplicate-arrays'] ? o[key].concat(value) : [o[key]].concat([value]) - } else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) { - o[key] = value - } else { - o[key] = o[key].concat([value]) - } - } else if (o[key] === undefined && isTypeArray) { - o[key] = isValueArray ? value : [value] - } else if (duplicate && !(o[key] === undefined || checkAllAliases(key, flags.bools) || checkAllAliases(keys.join('.'), flags.bools) || checkAllAliases(key, flags.counts))) { - o[key] = [ o[key], value ] - } else { - o[key] = value - } - } - - // extend the aliases list with inferred aliases. - function extendAliases () { - Array.prototype.slice.call(arguments).forEach(function (obj) { - Object.keys(obj || {}).forEach(function (key) { - // short-circuit if we've already added a key - // to the aliases array, for example it might - // exist in both 'opts.default' and 'opts.key'. - if (flags.aliases[key]) return - - flags.aliases[key] = [].concat(aliases[key] || []) - // For "--option-name", also set argv.optionName - flags.aliases[key].concat(key).forEach(function (x) { - if (/-/.test(x) && configuration['camel-case-expansion']) { - var c = camelCase(x) - flags.aliases[key].push(c) - newAliases[c] = true - } - }) - flags.aliases[key].forEach(function (x) { - flags.aliases[x] = [key].concat(flags.aliases[key].filter(function (y) { - return x !== y - })) - }) - }) - }) - } - - // check if a flag is set for any of a key's aliases. - function checkAllAliases (key, flag) { - var isSet = false - var toCheck = [].concat(flags.aliases[key] || [], key) - - toCheck.forEach(function (key) { - if (flag[key]) isSet = flag[key] - }) - - return isSet - } - - function setDefaulted (key) { - [].concat(flags.aliases[key] || [], key).forEach(function (k) { - flags.defaulted[k] = true - }) - } - - function unsetDefaulted (key) { - [].concat(flags.aliases[key] || [], key).forEach(function (k) { - delete flags.defaulted[k] - }) - } - - // return a default value, given the type of a flag., - // e.g., key of type 'string' will default to '', rather than 'true'. - function defaultForType (type) { - var def = { - boolean: true, - string: '', - number: undefined, - array: [] - } - - return def[type] - } - - // given a flag, enforce a default type. - function guessType (key, flags) { - var type = 'boolean' - - if (checkAllAliases(key, flags.strings)) type = 'string' - else if (checkAllAliases(key, flags.numbers)) type = 'number' - else if (checkAllAliases(key, flags.arrays)) type = 'array' - - return type - } - - function isNumber (x) { - if (!configuration['parse-numbers']) return false - if (typeof x === 'number') return true - if (/^0x[0-9a-f]+$/i.test(x)) return true - return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x) - } - - function isUndefined (num) { - return num === undefined - } - - return { - argv: argv, - error: error, - aliases: flags.aliases, - newAliases: newAliases, - configuration: configuration - } -} - -// if any aliases reference each other, we should -// merge them together. -function combineAliases (aliases) { - var aliasArrays = [] - var change = true - var combined = {} - - // turn alias lookup hash {key: ['alias1', 'alias2']} into - // a simple array ['key', 'alias1', 'alias2'] - Object.keys(aliases).forEach(function (key) { - aliasArrays.push( - [].concat(aliases[key], key) - ) - }) - - // combine arrays until zero changes are - // made in an iteration. - while (change) { - change = false - for (var i = 0; i < aliasArrays.length; i++) { - for (var ii = i + 1; ii < aliasArrays.length; ii++) { - var intersect = aliasArrays[i].filter(function (v) { - return aliasArrays[ii].indexOf(v) !== -1 - }) - - if (intersect.length) { - aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii]) - aliasArrays.splice(ii, 1) - change = true - break - } - } - } - } - - // map arrays back to the hash-lookup (de-dupe while - // we're at it). - aliasArrays.forEach(function (aliasArray) { - aliasArray = aliasArray.filter(function (v, i, self) { - return self.indexOf(v) === i - }) - combined[aliasArray.pop()] = aliasArray - }) - - return combined -} - -function assign (defaults, configuration) { - var o = {} - configuration = configuration || {} - - Object.keys(defaults).forEach(function (k) { - o[k] = defaults[k] - }) - Object.keys(configuration).forEach(function (k) { - o[k] = configuration[k] - }) - - return o -} - -// this function should only be called when a count is given as an arg -// it is NOT called to set a default value -// thus we can start the count at 1 instead of 0 -function increment (orig) { - return orig !== undefined ? orig + 1 : 1 -} - -function Parser (args, opts) { - var result = parse(args.slice(), opts) - - return result.argv -} - -// parse arguments and return detailed -// meta information, aliases, etc. -Parser.detailed = function (args, opts) { - return parse(args.slice(), opts) -} - -module.exports = Parser diff --git a/node_modules/webpack/node_modules/yargs-parser/lib/tokenize-arg-string.js b/node_modules/webpack/node_modules/yargs-parser/lib/tokenize-arg-string.js deleted file mode 100644 index 23d39e1fe..000000000 --- a/node_modules/webpack/node_modules/yargs-parser/lib/tokenize-arg-string.js +++ /dev/null @@ -1,34 +0,0 @@ -// take an un-split argv string and tokenize it. -module.exports = function (argString) { - if (Array.isArray(argString)) return argString - - var i = 0 - var c = null - var opening = null - var args = [] - - for (var ii = 0; ii < argString.length; ii++) { - c = argString.charAt(ii) - - // split on spaces unless we're in quotes. - if (c === ' ' && !opening) { - i++ - continue - } - - // don't split the string if we're in matching - // opening or closing single and double quotes. - if (c === opening) { - opening = null - continue - } else if ((c === "'" || c === '"') && !opening) { - opening = c - continue - } - - if (!args[i]) args[i] = '' - args[i] += c - } - - return args -} diff --git a/node_modules/webpack/node_modules/yargs-parser/package.json b/node_modules/webpack/node_modules/yargs-parser/package.json deleted file mode 100644 index 5d84e9f19..000000000 --- a/node_modules/webpack/node_modules/yargs-parser/package.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "name": "yargs-parser", - "version": "7.0.0", - "description": "the mighty option parser used by yargs", - "main": "index.js", - "scripts": { - "pretest": "standard", - "test": "nyc mocha test/*.js", - "coverage": "nyc report --reporter=text-lcov | coveralls", - "release": "standard-version" - }, - "repository": { - "url": "git@github.com:yargs/yargs-parser.git" - }, - "keywords": [ - "argument", - "parser", - "yargs", - "command", - "cli", - "parsing", - "option", - "args", - "argument" - ], - "author": "Ben Coe <ben@npmjs.com>", - "license": "ISC", - "devDependencies": { - "chai": "^3.5.0", - "coveralls": "^2.11.12", - "mocha": "^3.0.1", - "nyc": "^10.0.0", - "standard": "^10.0.2", - "standard-version": "^4.0.0" - }, - "dependencies": { - "camelcase": "^4.1.0" - }, - "files": [ - "lib", - "index.js" - ] -} diff --git a/node_modules/webpack/node_modules/yargs/CHANGELOG.md b/node_modules/webpack/node_modules/yargs/CHANGELOG.md deleted file mode 100644 index 95f414125..000000000 --- a/node_modules/webpack/node_modules/yargs/CHANGELOG.md +++ /dev/null @@ -1,961 +0,0 @@ -# Change Log - -All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. - -<a name="8.0.2"></a> -## [8.0.2](https://github.com/yargs/yargs/compare/v8.0.1...v8.0.2) (2017-06-12) - - - -<a name="8.0.1"></a> -## [8.0.1](https://github.com/yargs/yargs/compare/v8.0.0...v8.0.1) (2017-05-02) - - - -<a name="8.0.0"></a> -# [8.0.0](https://github.com/yargs/yargs/compare/v7.1.0...v8.0.0) (2017-05-01) - - -### Bug Fixes - -* commands are now applied in order, from left to right ([#857](https://github.com/yargs/yargs/issues/857)) ([baba863](https://github.com/yargs/yargs/commit/baba863)) -* help now takes precedence over command recommendation ([#866](https://github.com/yargs/yargs/issues/866)) ([17e3567](https://github.com/yargs/yargs/commit/17e3567)) -* positional arguments now work if no handler is provided to inner command ([#864](https://github.com/yargs/yargs/issues/864)) ([e28ded3](https://github.com/yargs/yargs/commit/e28ded3)) - - -### Chores - -* upgrade yargs-parser ([#867](https://github.com/yargs/yargs/issues/867)) ([8f9c6c6](https://github.com/yargs/yargs/commit/8f9c6c6)) - - -### Features - -* allow extends to inherit from a module ([#865](https://github.com/yargs/yargs/issues/865)) ([89456d9](https://github.com/yargs/yargs/commit/89456d9)) -* allow strict mode to be disabled ([#840](https://github.com/yargs/yargs/issues/840)) ([6f78c05](https://github.com/yargs/yargs/commit/6f78c05)) - - -### BREAKING CHANGES - -* extends functionality now always loads the JSON provided, rather than reading from a specific key -* Node 4+ is now required; this will allow us to start updating our dependencies. -* the first argument to strict() is now used to enable/disable its functionality, rather than controlling whether or not it is global. - - - -<a name="7.1.0"></a> -# [7.1.0](https://github.com/yargs/yargs/compare/v7.0.2...v7.1.0) (2017-04-13) - - -### Bug Fixes - -* fix demandOption no longer treats 'false' as truthy ([#829](https://github.com/yargs/yargs/issues/829)) ([c748dd2](https://github.com/yargs/yargs/commit/c748dd2)) -* get terminalWidth in non interactive mode no longer causes a validation exception ([#837](https://github.com/yargs/yargs/issues/837)) ([360e301](https://github.com/yargs/yargs/commit/360e301)) -* we shouldn't output help if we've printed a prior help-like message ([#847](https://github.com/yargs/yargs/issues/847)) ([17e89bd](https://github.com/yargs/yargs/commit/17e89bd)) - - -### Features - -* add support for numeric commands ([#825](https://github.com/yargs/yargs/issues/825)) ([fde0564](https://github.com/yargs/yargs/commit/fde0564)) - - - -<a name="7.0.2"></a> -## [7.0.2](https://github.com/yargs/yargs/compare/v7.0.1...v7.0.2) (2017-03-10) - - -### Bug Fixes - -* populating placeholder arguments broke validation ([b3eb2fe](https://github.com/yargs/yargs/commit/b3eb2fe)) - - - -<a name="7.0.1"></a> -## [7.0.1](https://github.com/yargs/yargs/compare/v7.0.0...v7.0.1) (2017-03-03) - - -### Bug Fixes - -* --help with default command should print top-level help ([#810](https://github.com/yargs/yargs/issues/810)) ([9c03fa4](https://github.com/yargs/yargs/commit/9c03fa4)) - - - -<a name="7.0.0"></a> -# [7.0.0](https://github.com/yargs/yargs/compare/v6.6.0...v7.0.0) (2017-02-26) - - -### Bug Fixes - -* address min/max validation message regression ([#750](https://github.com/yargs/yargs/issues/750)) ([2e5ce0f](https://github.com/yargs/yargs/commit/2e5ce0f)) -* address positional argument strict() bug introduced in [#766](https://github.com/yargs/yargs/issues/766) ([#784](https://github.com/yargs/yargs/issues/784)) ([a8528e6](https://github.com/yargs/yargs/commit/a8528e6)) -* console.warn() rather than throwing errors when api signatures are incorrect ([#804](https://github.com/yargs/yargs/issues/804)) ([a607061](https://github.com/yargs/yargs/commit/a607061)) -* context should override parsed argv ([#786](https://github.com/yargs/yargs/issues/786)) ([0997288](https://github.com/yargs/yargs/commit/0997288)) -* context variables are now recognized in strict() mode ([#796](https://github.com/yargs/yargs/issues/796)) ([48575cd](https://github.com/yargs/yargs/commit/48575cd)) -* errors were not bubbling appropriately from sub-commands to top-level ([#802](https://github.com/yargs/yargs/issues/802)) ([8a992f5](https://github.com/yargs/yargs/commit/8a992f5)) -* positional arguments of sub-commands threw strict() exception ([#805](https://github.com/yargs/yargs/issues/805)) ([f3f074b](https://github.com/yargs/yargs/commit/f3f074b)) -* pull in yargs-parser with modified env precedence ([#787](https://github.com/yargs/yargs/issues/787)) ([e0fbbe5](https://github.com/yargs/yargs/commit/e0fbbe5)) -* running parse() multiple times on the same yargs instance caused exception if help() enabled ([#790](https://github.com/yargs/yargs/issues/790)) ([07e39b7](https://github.com/yargs/yargs/commit/07e39b7)) -* use path.resolve() to support node 0.10 ([#797](https://github.com/yargs/yargs/issues/797)) ([49a93fc](https://github.com/yargs/yargs/commit/49a93fc)) - - -### Features - -* add conflicts and implies shorthands. ([#753](https://github.com/yargs/yargs/issues/753)) ([bd1472b](https://github.com/yargs/yargs/commit/bd1472b)) -* add traditional Chinese translation ([#780](https://github.com/yargs/yargs/issues/780)) ([6ab6a95](https://github.com/yargs/yargs/commit/6ab6a95)) -* allow provided config object to extend other configs ([#779](https://github.com/yargs/yargs/issues/779)) ([3280dd0](https://github.com/yargs/yargs/commit/3280dd0)) -* function argument validation ([#773](https://github.com/yargs/yargs/issues/773)) ([22ed9bb](https://github.com/yargs/yargs/commit/22ed9bb)) -* if only one column is provided for examples, allow it to take up the entire line ([#749](https://github.com/yargs/yargs/issues/749)) ([7931652](https://github.com/yargs/yargs/commit/7931652)) -* introduce custom yargs error object ([#765](https://github.com/yargs/yargs/issues/765)) ([8308efa](https://github.com/yargs/yargs/commit/8308efa)) -* introduces support for default commands, using the '*' identifier ([#785](https://github.com/yargs/yargs/issues/785)) ([d78a0f5](https://github.com/yargs/yargs/commit/d78a0f5)) -* rethink how options are inherited by commands ([#766](https://github.com/yargs/yargs/issues/766)) ([ab1fa4b](https://github.com/yargs/yargs/commit/ab1fa4b)) - - -### BREAKING CHANGES - -* `extends` key in config file is now used for extending other config files -* environment variables now take precedence over config files. -* context now takes precedence over argv and defaults -* the arguments passed to functions are now validated, there's a good chance this will throw exceptions for a few folks who are using the API in an unexpected way. -* by default options, and many of yargs' parsing helpers will now default to being applied globally; such that they are no-longer reset before being passed into commands. -* yargs will no longer aggressively suppress errors, allowing errors that are not generated internally to bubble. - - - -<a name="6.6.0"></a> -# [6.6.0](https://github.com/yargs/yargs/compare/v6.5.0...v6.6.0) (2016-12-29) - - -### Bug Fixes - -* [object Object] was accidentally being populated on options object ([#736](https://github.com/yargs/yargs/issues/736)) ([f755e27](https://github.com/yargs/yargs/commit/f755e27)) -* do not use cwd when resolving package.json for yargs parsing config ([#726](https://github.com/yargs/yargs/issues/726)) ([9bdaab7](https://github.com/yargs/yargs/commit/9bdaab7)) - - -### Features - -* implement conflicts() for defining mutually exclusive arguments; thanks [@madcampos](https://github.com/madcampos)! ([#741](https://github.com/yargs/yargs/issues/741)) ([5883779](https://github.com/yargs/yargs/commit/5883779)) -* split demand() into demandCommand()/demandOption() ([#740](https://github.com/yargs/yargs/issues/740)) ([66573c8](https://github.com/yargs/yargs/commit/66573c8)) -* support for positional argument aliases ([#727](https://github.com/yargs/yargs/issues/727)) ([27e1a57](https://github.com/yargs/yargs/commit/27e1a57)) - - - -<a name="6.5.0"></a> -# [6.5.0](https://github.com/yargs/yargs/compare/v6.4.0...v6.5.0) (2016-12-01) - - -### Bug Fixes - -* still freeze/unfreeze if parse() is called in isolation ([#717](https://github.com/yargs/yargs/issues/717)) ([30a9492](https://github.com/yargs/yargs/commit/30a9492)) - - -### Features - -* pull in yargs-parser introducing additional settings ([#688](https://github.com/yargs/yargs/issues/688)), and fixing [#716](https://github.com/yargs/yargs/issues/716) ([#722](https://github.com/yargs/yargs/issues/722)) ([702995a](https://github.com/yargs/yargs/commit/702995a)) - - - -<a name="6.4.0"></a> -# [6.4.0](https://github.com/yargs/yargs/compare/v6.3.0...v6.4.0) (2016-11-13) - - -### Bug Fixes - -* **locales:** correct some Russian translations ([#691](https://github.com/yargs/yargs/issues/691)) ([a980671](https://github.com/yargs/yargs/commit/a980671)) - - -### Features - -* **locales:** Added Belarusian translation ([#690](https://github.com/yargs/yargs/issues/690)) ([68dac1f](https://github.com/yargs/yargs/commit/68dac1f)) -* **locales:** Create nl.json ([#687](https://github.com/yargs/yargs/issues/687)) ([46ce1bb](https://github.com/yargs/yargs/commit/46ce1bb)) -* update to yargs-parser that addresses [#598](https://github.com/yargs/yargs/issues/598), [#617](https://github.com/yargs/yargs/issues/617) ([#700](https://github.com/yargs/yargs/issues/700)) ([54cb31d](https://github.com/yargs/yargs/commit/54cb31d)) -* yargs is now passed as the third-argument to fail handler ([#613](https://github.com/yargs/yargs/issues/613)) ([21b74f9](https://github.com/yargs/yargs/commit/21b74f9)) - - -### Performance Improvements - -* normalizing package data is an expensive operation ([#705](https://github.com/yargs/yargs/issues/705)) ([49cf533](https://github.com/yargs/yargs/commit/49cf533)) - - - -<a name="6.3.0"></a> -# [6.3.0](https://github.com/yargs/yargs/compare/v6.2.0...v6.3.0) (2016-10-19) - - -### Bug Fixes - -* **command:** subcommands via commandDir() now supported for parse(msg, cb) ([#678](https://github.com/yargs/yargs/issues/678)) ([6b85cc6](https://github.com/yargs/yargs/commit/6b85cc6)) - - -### Features - -* **locales:** Add Thai locale file ([#679](https://github.com/yargs/yargs/issues/679)) ([c05e36b](https://github.com/yargs/yargs/commit/c05e36b)) - - - -<a name="6.2.0"></a> -# [6.2.0](https://github.com/yargs/yargs/compare/v6.1.1...v6.2.0) (2016-10-16) - - -### Bug Fixes - -* stop applying parser to context object ([#675](https://github.com/yargs/yargs/issues/675)) ([3fe9b8f](https://github.com/yargs/yargs/commit/3fe9b8f)) - - -### Features - -* add new pt_BR translations ([#674](https://github.com/yargs/yargs/issues/674)) ([5615a82](https://github.com/yargs/yargs/commit/5615a82)) -* Italian translations for 'did you mean' and 'aliases' ([#673](https://github.com/yargs/yargs/issues/673)) ([81984e6](https://github.com/yargs/yargs/commit/81984e6)) - - - -<a name="6.1.1"></a> -## [6.1.1](https://github.com/yargs/yargs/compare/v6.1.0...v6.1.1) (2016-10-15) - - -### Bug Fixes - -* freeze was not resetting configObjects to initial state; addressed performance issue raised by [@nexdrew](https://github.com/nexdrew). ([#670](https://github.com/yargs/yargs/issues/670)) ([ae4bcd4](https://github.com/yargs/yargs/commit/ae4bcd4)) - - - -<a name="6.1.0"></a> -# [6.1.0](https://github.com/yargs/yargs/compare/v6.0.0...v6.1.0) (2016-10-15) - - -### Bug Fixes - -* **locales:** change some translations ([#667](https://github.com/yargs/yargs/issues/667)) ([aa966c5](https://github.com/yargs/yargs/commit/aa966c5)) -* **locales:** conform hi locale to y18n.__n expectations ([#666](https://github.com/yargs/yargs/issues/666)) ([22adb18](https://github.com/yargs/yargs/commit/22adb18)) - - -### Features - -* initial support for command aliases ([#647](https://github.com/yargs/yargs/issues/647)) ([127a040](https://github.com/yargs/yargs/commit/127a040)) -* **command:** add camelcase commands to argv ([#658](https://github.com/yargs/yargs/issues/658)) ([b1cabae](https://github.com/yargs/yargs/commit/b1cabae)) -* **locales:** add Hindi translations ([9290912](https://github.com/yargs/yargs/commit/9290912)) -* **locales:** add Hungarian translations ([be92327](https://github.com/yargs/yargs/commit/be92327)) -* **locales:** Japanese translations for 'did you mean' and 'aliases' ([#651](https://github.com/yargs/yargs/issues/651)) ([5eb78fc](https://github.com/yargs/yargs/commit/5eb78fc)) -* **locales:** Polish translations for 'did you mean' and 'aliases' ([#650](https://github.com/yargs/yargs/issues/650)) ([c951c0e](https://github.com/yargs/yargs/commit/c951c0e)) -* reworking yargs API to make it easier to run in headless environments, e.g., Slack ([#646](https://github.com/yargs/yargs/issues/646)) ([f284c29](https://github.com/yargs/yargs/commit/f284c29)) -* Turkish translations for 'did you mean' and 'aliases' ([#660](https://github.com/yargs/yargs/issues/660)) ([072fd45](https://github.com/yargs/yargs/commit/072fd45)) - - - -<a name="6.0.0"></a> -# [6.0.0](https://github.com/yargs/yargs/compare/v5.0.0...v6.0.0) (2016-09-30) - - -### Bug Fixes - -* changed parsing of the command string to ignore extra spaces ([#600](https://github.com/yargs/yargs/issues/600)) ([e8e5a72](https://github.com/yargs/yargs/commit/e8e5a72)) -* drop lodash.assign ([#641](https://github.com/yargs/yargs/issues/641)) ([ad3146f](https://github.com/yargs/yargs/commit/ad3146f)) -* for args that have skipValidation set to `true`, check if the parsed arg is `true` ([#619](https://github.com/yargs/yargs/issues/619)) ([658a34c](https://github.com/yargs/yargs/commit/658a34c)) -* upgrade standard, and fix appveyor config so that it works with newest standard ([#607](https://github.com/yargs/yargs/issues/607)) ([c301f42](https://github.com/yargs/yargs/commit/c301f42)) - - -### Chores - -* upgrade yargs-parser ([#633](https://github.com/yargs/yargs/issues/633)) ([cc1224e](https://github.com/yargs/yargs/commit/cc1224e)) - - -### Features - -* make opts object optional for .option() ([#624](https://github.com/yargs/yargs/issues/624)) ([4f29de6](https://github.com/yargs/yargs/commit/4f29de6)) - - -### Performance Improvements - -* defer windowWidth() to improve perf for non-help usage ([#610](https://github.com/yargs/yargs/issues/610)) ([cbc3636](https://github.com/yargs/yargs/commit/cbc3636)) - - -### BREAKING CHANGES - -* coerce is now applied as a final step after other parsing is complete - - - -<a name="5.0.0"></a> -# [5.0.0](https://github.com/yargs/yargs/compare/v4.8.1...v5.0.0) (2016-08-14) - - -### Bug Fixes - -* **default:** Remove undocumented alias of default() ([#469](https://github.com/yargs/yargs/issues/469)) ([b8591b2](https://github.com/yargs/yargs/commit/b8591b2)) -* remove deprecated zh.json ([#578](https://github.com/yargs/yargs/issues/578)) ([317c62c](https://github.com/yargs/yargs/commit/317c62c)) - - -### Features - -* .help() API can now enable implicit help command ([#574](https://github.com/yargs/yargs/issues/574)) ([7645019](https://github.com/yargs/yargs/commit/7645019)) -* **command:** builder function no longer needs to return the yargs instance ([#549](https://github.com/yargs/yargs/issues/549)) ([eaa2873](https://github.com/yargs/yargs/commit/eaa2873)) -* add coerce api ([#586](https://github.com/yargs/yargs/issues/586)) ([1d53ccb](https://github.com/yargs/yargs/commit/1d53ccb)) -* adds recommendCommands() for command suggestions ([#580](https://github.com/yargs/yargs/issues/580)) ([59474dc](https://github.com/yargs/yargs/commit/59474dc)) -* apply .env() globally ([#553](https://github.com/yargs/yargs/issues/553)) ([be65728](https://github.com/yargs/yargs/commit/be65728)) -* apply default builder to command() and apply fail() handlers globally ([#583](https://github.com/yargs/yargs/issues/583)) ([0aaa68b](https://github.com/yargs/yargs/commit/0aaa68b)) -* update yargs-parser to version 3.1.0 ([#581](https://github.com/yargs/yargs/issues/581)) ([882a127](https://github.com/yargs/yargs/commit/882a127)) - - -### Performance Improvements - -* defer requiring most external libs until needed ([#584](https://github.com/yargs/yargs/issues/584)) ([f9b0ed4](https://github.com/yargs/yargs/commit/f9b0ed4)) - - -### BREAKING CHANGES - -* fail is now applied globally. -* we now default to an empty builder function when command is executed with no builder. -* yargs-parser now better handles negative integer values, at the cost of handling numeric option names, e.g., -1 hello -* default: removed undocumented `defaults` alias for `default`. -* introduces a default `help` command which outputs help, as an alternative to a help flag. -* interpret demand() numbers as relative to executing command ([#582](https://github.com/yargs/yargs/issues/582)) ([927810c](https://github.com/yargs/yargs/commit/927810c)) - - - -<a name="4.8.1"></a> -## [4.8.1](https://github.com/yargs/yargs/compare/v4.8.0...v4.8.1) (2016-07-16) - - -### Bug Fixes - -* **commandDir:** make dir relative to caller instead of require.main.filename ([#548](https://github.com/yargs/yargs/issues/548)) ([3c2e479](https://github.com/yargs/yargs/commit/3c2e479)) -* add config lookup for .implies() ([#556](https://github.com/yargs/yargs/issues/556)) ([8d7585c](https://github.com/yargs/yargs/commit/8d7585c)) -* cache pkg lookups by path to avoid returning the wrong one ([#552](https://github.com/yargs/yargs/issues/552)) ([fea7e0b](https://github.com/yargs/yargs/commit/fea7e0b)) -* positional arguments were not being handled appropriately by parse() ([#559](https://github.com/yargs/yargs/issues/559)) ([063a866](https://github.com/yargs/yargs/commit/063a866)) -* pull in [@nexdrew](https://github.com/nexdrew)'s fixes to yargs-parser ([#560](https://github.com/yargs/yargs/issues/560)) ([c77c080](https://github.com/yargs/yargs/commit/c77c080)), closes [#560](https://github.com/yargs/yargs/issues/560) - - - -<a name="4.8.0"></a> -# [4.8.0](https://github.com/yargs/yargs/compare/v4.7.1...v4.8.0) (2016-07-09) - - -### Bug Fixes - -* drop unused camelcase dependency fixes [#516](https://github.com/yargs/yargs/issues/516) ([#525](https://github.com/yargs/yargs/issues/525)) ([365fb9a](https://github.com/yargs/yargs/commit/365fb9a)), closes [#516](https://github.com/yargs/yargs/issues/516) [#525](https://github.com/yargs/yargs/issues/525) -* fake a tty in tests, so that we can use the new set-blocking ([#512](https://github.com/yargs/yargs/issues/512)) ([a54c742](https://github.com/yargs/yargs/commit/a54c742)) -* ignore invalid package.json during read-pkg-up ([#546](https://github.com/yargs/yargs/issues/546)) ([e058c87](https://github.com/yargs/yargs/commit/e058c87)) -* keep both zh and zh_CN until yargs[@5](https://github.com/5).x ([0f8faa7](https://github.com/yargs/yargs/commit/0f8faa7)) -* lazy-load package.json and cache. get rid of pkg-conf dependency. ([#544](https://github.com/yargs/yargs/issues/544)) ([2609b2e](https://github.com/yargs/yargs/commit/2609b2e)) -* we now respect the order of _ when applying commands ([#537](https://github.com/yargs/yargs/issues/537)) ([ed86b78](https://github.com/yargs/yargs/commit/ed86b78)) - - -### Features - -* add .commandDir(dir) to API to apply all command modules from a relative directory ([#494](https://github.com/yargs/yargs/issues/494)) ([b299dff](https://github.com/yargs/yargs/commit/b299dff)) -* **command:** derive missing command string from module filename ([#527](https://github.com/yargs/yargs/issues/527)) ([20d4b8a](https://github.com/yargs/yargs/commit/20d4b8a)) -* builder is now optional for a command module ([#545](https://github.com/yargs/yargs/issues/545)) ([8d6ad6e](https://github.com/yargs/yargs/commit/8d6ad6e)) - - - -<a name="4.7.1"></a> -## [4.7.1](https://github.com/yargs/yargs/compare/v4.7.0...v4.7.1) (2016-05-15) - - -### Bug Fixes - -* switch to using `const` rather than `var` ([#499](https://github.com/yargs/yargs/pull/499)) -* make stdout flush on newer versions of Node.js ([#501](https://github.com/yargs/yargs/issues/501)) ([9f8c6f4](https://github.com/yargs/yargs/commit/9f8c6f4)) - - - -<a name="4.7.0"></a> -# [4.7.0](https://github.com/yargs/yargs/compare/v4.6.0...v4.7.0) (2016-05-02) - - -### Bug Fixes - -* **pkgConf:** fix aliases issues in .pkgConf() ([#478](https://github.com/yargs/yargs/issues/478))([b900502](https://github.com/yargs/yargs/commit/b900502)) - - -### Features - -* **completion:** allow to get completions for any string, not just process.argv ([#470](https://github.com/yargs/yargs/issues/470))([74fcfbc](https://github.com/yargs/yargs/commit/74fcfbc)) -* **configuration:** Allow to directly pass a configuration object to .config() ([#480](https://github.com/yargs/yargs/issues/480))([e0a7e05](https://github.com/yargs/yargs/commit/e0a7e05)) -* **validation:** Add .skipValidation() method ([#471](https://github.com/yargs/yargs/issues/471))([d72badb](https://github.com/yargs/yargs/commit/d72badb)) - - - -<a name="4.6.0"></a> -# [4.6.0](https://github.com/yargs/yargs/compare/v4.5.0...v4.6.0) (2016-04-11) - - -### Bug Fixes - -* **my brand!:** I agree with [@osher](https://github.com/osher) lightweight isn't a huge selling point of ours any longer, see [#468](https://github.com/yargs/yargs/issues/468) ([c46d7e1](https://github.com/yargs/yargs/commit/c46d7e1)) - -### Features - -* switch to standard-version for release management ([f70f801](https://github.com/yargs/yargs/commit/f70f801)) -* upgrade to version of yargs-parser that introduces some slick new features, great work [@elas7](https://github.com/elas7). update cliui, replace win-spawn, replace badge. ([#475](https://github.com/yargs/yargs/issues/475)) ([f915dd4](https://github.com/yargs/yargs/commit/f915dd4)) - - - -<a name="4.5.0"></a> -# [4.5.0](https://github.com/yargs/yargs/compare/v4.4.0...v4.5.0) (2016-04-05) - - -### Bug Fixes - -* **windows:** handle $0 better on Windows platforms ([eb6e03f](https://github.com/yargs/yargs/commit/eb6e03f)) - -### Features - -* **commands:** implemented variadic positional arguments ([51d926e](https://github.com/yargs/yargs/commit/51d926e)) -* **completion:** completion now better handles aliases, and avoids duplicating keys. ([86416c8](https://github.com/yargs/yargs/commit/86416c8)) -* **config:** If invoking .config() without parameters, set a default option ([0413dd1](https://github.com/yargs/yargs/commit/0413dd1)) -* **conventional-changelog:** switching to using conventional-changelog for generating the changelog ([a2b5a2a](https://github.com/yargs/yargs/commit/a2b5a2a)) - - - -### v4.4.0 (2016/04/03 21:10 +07:00) - -- [#454](https://github.com/yargs/yargs/pull/454) fix demand() when second argument is an array (@elas7) -- [#452](https://github.com/yargs/yargs/pull/452) fix code example for `.help()` docs (@maxrimue) -- [#450](https://github.com/yargs/yargs/pull/450) fix for bash completion trailing space edge-case (@elas7) -- [#448](https://github.com/yargs/yargs/pull/448) allow a method to be passed to `showHelp`, rather than a log-level (@osher) -- [#446](https://github.com/yargs/yargs/pull/446) update yargs-parser, y18n, nyc, cliui, pkg-conf (@bcoe) -- [#436](https://github.com/yargs/yargs/pull/436) the rebase method is only used by tests, do not export it in two places (@elas7) -- [#428](https://github.com/yargs/yargs/pull/428) initial support for subcommands (@nexdrew) - -### v4.3.2 (2016/3/20 15:07 +07:00) - -- [#445](https://github.com/yargs/yargs/pull/445) strict mode was failing if no commands were registered (@nexdrew) -- [#443](https://github.com/yargs/yargs/pull/443) adds Italian translation \o/ (@madrisan) -- [#441](https://github.com/yargs/yargs/pull/441) remove duplicate keys from array options configuration (@elas7) -- [#437](https://github.com/yargs/yargs/pull/437) standardize tests for .command() (@lrlna) - -### v4.3.0 (2016/3/12 14:19 +07:00) - -- [#432](https://github.com/yargs/yargs/pull/432) non-singleton version of yargs (@bcoe) -- [#422, #425, #420] translations for number (@zkat, @rilut, @maxrimue, @watilde) -- [#414](https://github.com/yargs/yargs/pull/414) all command options can be defined in module now (@nexdrew) - -### v4.2.0 (2016/2/22 11:02 +07:00) - -- [#395](https://github.com/yargs/yargs/pull/395) do not reset groups if they contain - global keys (@novemberborn) -- [#393](https://github.com/yargs/yargs/pull/393) use sane default for usage strings (@nexdrew) -- [#392](https://github.com/yargs/yargs/pull/392) resetting wrap() was causing layout issues - with commands (@nexdrew) -- [#391](https://github.com/yargs/yargs/pull/391) commands were being added multiple times (@nexdrew) - -### v4.0.0 (2016/2/14 1:27 +07:00) - -- [#384](https://github.com/bcoe/yargs/pull/384) add new number type to yargs (@lrlna, @maxrimue) -- [#382](https://github.com/bcoe/yargs/pull/382) pass error as extra parameter to fail (@gajus) -- [#378](https://github.com/bcoe/yargs/pull/378) introduces the pkgConf feature, which tells - yargs to load default argument values from a key on a project's package.json (@bcoe) -- [#376](https://github.com/bcoe/yargs/pull/376) **breaking change**, make help() method signature - more consistent with other commands (@maxrimue) -- [#368](https://github.com/bcoe/yargs/pull/368) **breaking change**, overhaul to command handling API: - introducing named positional arguments, commands as modules, introduces the concept of global options (options that don't reset). (@nexdrew, @bcoe). -- [#364](https://github.com/bcoe/yargs/pull/364) add the slick new yargs website to the package.json (@iarna). -- [#357](https://github.com/bcoe/yargs/pull/357) .strict() now requires that a valid command is provided (@lrlna) -- [#356](https://github.com/bcoe/yargs/pull/356) pull the parsing bits of yargs into the separate module yargs-parser. Various parsing options can now be turned on and off using configuration (@bcoe). -- [#330](https://github.com/bcoe/yargs/pull/330) **breaking change**, fix inconsistencies with `.version()` API. (@maxrimue). - -### v3.32.0 (2016/1/14 10:13 +07:00) - -- [#344](https://github.com/bcoe/yargs/pull/344) yargs now has a code of conduct and contributor guidelines (@bcoe) -- [#341](https://github.com/bcoe/yargs/issues/341) Fix edge-case with camel-case arguments (@davibe) -- [#331](https://github.com/bcoe/yargs/pull/331) Handle parsing a raw argument string (@kellyselden) -- [#325](https://github.com/bcoe/yargs/pull/325) Tweaks to make tests pass again on Windows (@isaacs) -- [#321](https://github.com/bcoe/yargs/pull/321) Custom config parsing function (@bcoe) - -### v3.31.0 (2015/12/03 10:15 +07:00) - -- [#239](https://github.com/bcoe/yargs/pull/239) Pass argv to commands (@bcoe) -- [#308](https://github.com/bcoe/yargs/pull/308) Yargs now handles environment variables (@nexdrew) -- [#302](https://github.com/bcoe/yargs/pull/302) Add Indonesian translation (@rilut) -- [#300](https://github.com/bcoe/yargs/pull/300) Add Turkish translation (@feyzo) -- [#298](https://github.com/bcoe/yargs/pull/298) Add Norwegian Bokmål translation (@sindresorhus) -- [#297](https://github.com/bcoe/yargs/pull/297) Fix for layout of cjk characters (@disjukr) -- [#296](https://github.com/bcoe/yargs/pull/296) Add Korean translation (@disjukr) - -### v3.30.0 (2015/11/13 16:29 +07:00) - -- [#293](https://github.com/bcoe/yargs/pull/293) Polish language support (@kamilogorek) -- [#291](https://github.com/bcoe/yargs/pull/291) fix edge-cases with `.alias()` (@bcoe) -- [#289](https://github.com/bcoe/yargs/pull/289) group options in custom groups (@bcoe) - -### v3.29.0 (2015/10/16 21:51 +07:00) - -- [#282](https://github.com/bcoe/yargs/pull/282) completions now accept promises (@LinusU) -- [#281](https://github.com/bcoe/yargs/pull/281) fix parsing issues with dot notation (@bcoe) - -### v3.28.0 (2015/10/16 1:55 +07:00) - -- [#277](https://github.com/bcoe/yargs/pull/277) adds support for ansi escape codes (@bcoe) - -### v3.27.0 (2015/10/08 1:55 +00:00) - -- [#271](https://github.com/bcoe/yargs/pull/273) skips validation for help or version flags with exitProcess(false) (@tepez) -- [#273](https://github.com/bcoe/yargs/pull/273) implements single output for errors with exitProcess(false) (@nexdrew) -- [#269](https://github.com/bcoe/yargs/pull/269) verifies single output for errors with exitProcess(false) (@tepez) -- [#268](https://github.com/bcoe/yargs/pull/268) adds Chinese translation (@qiu8310) -- [#266](https://github.com/bcoe/yargs/pull/266) adds case for -- after -- in parser test (@geophree) - -### v3.26.0 (2015/09/25 2:14 +00:00) - -- [#263](https://github.com/bcoe/yargs/pull/263) document count() and option() object keys (@nexdrew) -- [#259](https://github.com/bcoe/yargs/pull/259) remove util in readme (@38elements) -- [#258](https://github.com/bcoe/yargs/pull/258) node v4 builds, update deps (@nexdrew) -- [#257](https://github.com/bcoe/yargs/pull/257) fix spelling errors (@dkoleary88) - -### v3.25.0 (2015/09/13 7:38 -07:00) - -- [#254](https://github.com/bcoe/yargs/pull/254) adds Japanese translation (@oti) -- [#253](https://github.com/bcoe/yargs/pull/253) fixes for tests on Windows (@bcoe) - -### v3.24.0 (2015/09/04 12:02 +00:00) - -- [#248](https://github.com/bcoe/yargs/pull/248) reinstate os-locale, no spawning (@nexdrew) -- [#249](https://github.com/bcoe/yargs/pull/249) use travis container-based infrastructure (@nexdrew) -- [#247](https://github.com/bcoe/yargs/pull/247) upgrade standard (@nexdrew) - -### v3.23.0 (2015/08/30 23:00 +00:00) - -- [#246](https://github.com/bcoe/yargs/pull/246) detect locale based only on environment variables (@bcoe) -- [#244](https://github.com/bcoe/yargs/pull/244) adds Windows CI testing (@bcoe) -- [#245](https://github.com/bcoe/yargs/pull/245) adds OSX CI testing (@bcoe, @nexdrew) - -### v3.22.0 (2015/08/28 22:26 +00:00) -- [#242](https://github.com/bcoe/yargs/pull/242) adds detectLocale config option (@bcoe) - -### v3.21.1 (2015/08/28 20:58 +00:00) -- [#240](https://github.com/bcoe/yargs/pull/240) hot-fix for Atom on Windows (@bcoe) - -### v3.21.0 (2015/08/21 21:20 +00:00) -- [#238](https://github.com/bcoe/yargs/pull/238) upgrade camelcase, window-size, chai, mocha (@nexdrew) -- [#237](https://github.com/bcoe/yargs/pull/237) adds defaultDescription to option() (@nexdrew) - -### v3.20.0 (2015/08/20 01:29 +00:00) -- [#231](https://github.com/bcoe/yargs/pull/231) Merge pull request #231 from bcoe/detect-locale (@sindresorhus) -- [#235](https://github.com/bcoe/yargs/pull/235) adds german translation to yargs (@maxrimue) - -### v3.19.0 (2015/08/14 05:12 +00:00) -- [#224](https://github.com/bcoe/yargs/pull/224) added Portuguese translation (@codemonkey3045) - -### v3.18.1 (2015/08/12 05:53 +00:00) - -- [#228](https://github.com/bcoe/yargs/pull/228) notes about embedding yargs in Electron (@etiktin) -- [#223](https://github.com/bcoe/yargs/pull/223) make booleans work in config files (@sgentle) - -### v3.18.0 (2015/08/06 20:05 +00:00) -- [#222](https://github.com/bcoe/yargs/pull/222) updates fr locale (@nexdrew) -- [#221](https://github.com/bcoe/yargs/pull/221) adds missing locale strings (@nexdrew) -- [#220](https://github.com/bcoe/yargs/pull/220) adds es locale (@zkat) - -### v3.17.1 (2015/08/02 19:35 +00:00) -- [#218](https://github.com/bcoe/yargs/pull/218) upgrades nyc (@bcoe) - -### v3.17.0 (2015/08/02 18:39 +00:00) -- [#217](https://github.com/bcoe/yargs/pull/217) sort methods in README.md (@nexdrew) -- [#215](https://github.com/bcoe/yargs/pull/215) adds fr locale (@LoicMahieu) - -### v3.16.0 (2015/07/30 04:35 +00:00) -- [#210](https://github.com/bcoe/yargs/pull/210) adds i18n support to yargs (@bcoe) -- [#209](https://github.com/bcoe/yargs/pull/209) adds choices type to yargs (@nexdrew) -- [#207](https://github.com/bcoe/yargs/pull/207) pretty new shields from shields.io (@SimenB) -- [#208](https://github.com/bcoe/yargs/pull/208) improvements to README.md (@nexdrew) -- [#205](https://github.com/bcoe/yargs/pull/205) faster build times on Travis (@ChristianMurphy) - -### v3.15.0 (2015/07/06 06:01 +00:00) -- [#197](https://github.com/bcoe/yargs/pull/197) tweaks to how errors bubble up from parser.js (@bcoe) -- [#193](https://github.com/bcoe/yargs/pull/193) upgraded nyc, reporting now happens by default (@bcoe) - -### v3.14.0 (2015/06/28 02:12 +00:00) - -- [#192](https://github.com/bcoe/yargs/pull/192) standard style nits (@bcoe) -- [#190](https://github.com/bcoe/yargs/pull/190) allow for hidden commands, e.g., - .completion('completion', false) (@tschaub) - -### v3.13.0 (2015/06/24 04:12 +00:00) - -- [#187](https://github.com/bcoe/yargs/pull/187) completion now behaves differently - if it is being run in the context of a command (@tschaub) -- [#186](https://github.com/bcoe/yargs/pull/186) if no matches are found for a completion - default to filename completion (@tschaub) - -### v3.12.0 (2015/06/19 03:23 +00:00) -- [#183](https://github.com/bcoe/yargs/pull/183) don't complete commands if they've already been completed (@tschaub) -- [#181](https://github.com/bcoe/yargs/pull/181) various fixes for completion. (@bcoe, @tschaub) -- [#182](https://github.com/bcoe/yargs/pull/182) you can now set a maximum # of of required arguments (@bcoe) - -### v3.11.0 (2015/06/15 05:15 +00:00) - -- [#173](https://github.com/bcoe/yargs/pull/173) update standard, window-size, chai (@bcoe) -- [#171](https://github.com/bcoe/yargs/pull/171) a description can now be set - when providing a config option. (@5c077yP) - -### v3.10.0 (2015/05/29 04:25 +00:00) - -- [#165](https://github.com/bcoe/yargs/pull/165) expose yargs.terminalWidth() thanks @ensonic (@bcoe) -- [#164](https://github.com/bcoe/yargs/pull/164) better array handling thanks @getify (@bcoe) - -### v3.9.1 (2015/05/20 05:14 +00:00) -- [b6662b6](https://github.com/bcoe/yargs/commit/b6662b6774cfeab4876f41ec5e2f67b7698f4e2f) clarify .config() docs (@linclark) -- [0291360](https://github.com/bcoe/yargs/commit/02913606285ce31ce81d7f12c48d8a3029776ec7) fixed tests, switched to nyc for coverage, fixed security issue, added Lin as collaborator (@bcoe) - -### v3.9.0 (2015/05/10 18:32 +00:00) -- [#157](https://github.com/bcoe/yargs/pull/157) Merge pull request #157 from bcoe/command-yargs. allows handling of command specific arguments. Thanks for the suggestion @ohjames (@bcoe) -- [#158](https://github.com/bcoe/yargs/pull/158) Merge pull request #158 from kemitchell/spdx-license. Update license format (@kemitchell) - -### v3.8.0 (2015/04/24 23:10 +00:00) -- [#154](https://github.com/bcoe/yargs/pull/154) showHelp's method signature was misleading fixes #153 (@bcoe) -- [#151](https://github.com/bcoe/yargs/pull/151) refactor yargs' table layout logic to use new helper library (@bcoe) -- [#150](https://github.com/bcoe/yargs/pull/150) Fix README example in argument requirements (@annonymouse) - -### v3.7.2 (2015/04/13 11:52 -07:00) - -* [679fbbf](https://github.com/bcoe/yargs/commit/679fbbf55904030ccee8a2635e8e5f46551ab2f0) updated yargs to use the [standard](https://github.com/feross/standard) style guide (agokjr) -* [22382ee](https://github.com/bcoe/yargs/commit/22382ee9f5b495bc2586c1758cd1091cec3647f9 various bug fixes for $0 (@nylen) - -### v3.7.1 (2015/04/10 11:06 -07:00) - -* [89e1992](https://github.com/bcoe/yargs/commit/89e1992a004ba73609b5f9ee6890c4060857aba4) detect iojs bin along with node bin. (@bcoe) -* [755509e](https://github.com/bcoe/yargs/commit/755509ea90041e5f7833bba3b8c5deffe56f0aab) improvements to example documentation in README.md (@rstacruz) -* [0d2dfc8](https://github.com/bcoe/yargs/commit/0d2dfc822a43418242908ad97ddd5291a1b35dc6) showHelp() no longer requires that .argv has been called (@bcoe) - -### v3.7.0 (2015/04/04 02:29 -07:00) - -* [56cbe2d](https://github.com/bcoe/yargs/commit/56cbe2ddd33dc176dcbf97ba40559864a9f114e4) make .requiresArg() work with type hints. (@bcoe). -* [2f5d562](https://github.com/bcoe/yargs/commit/2f5d5624f736741deeedf6a664d57bc4d857bdd0) serialize arrays and objects in usage strings. (@bcoe). -* [5126304](https://github.com/bcoe/yargs/commit/5126304dd18351fc28f10530616fdd9361e0af98) be more lenient about alias/primary key ordering in chaining API. (@bcoe) - -### v3.6.0 (2015/03/21 01:00 +00:00) -- [4e24e22](https://github.com/bcoe/yargs/commit/4e24e22e6a195e55ab943ede704a0231ac33b99c) support for .js configuration files. (@pirxpilot) - -### v3.5.4 (2015/03/12 05:56 +00:00) -- [c16cc08](https://github.com/bcoe/yargs/commit/c16cc085501155cf7fd853ccdf8584b05ab92b78) message for non-option arguments is now optional, thanks to (@raine) - -### v3.5.3 (2015/03/09 06:14 +00:00) -- [870b428](https://github.com/bcoe/yargs/commit/870b428cf515d560926ca392555b7ad57dba9e3d) completion script was missing in package.json (@bcoe) - -### v3.5.2 (2015/03/09 06:11 +00:00) -- [58a4b24](https://github.com/bcoe/yargs/commit/58a4b2473ebbb326713d522be53e32d3aabb08d2) parse was being called multiple times, resulting in strange behavior (@bcoe) - -### v3.5.1 (2015/03/09 04:55 +00:00) -- [4e588e0](https://github.com/bcoe/yargs/commit/4e588e055afbeb9336533095f051496e3977f515) accidentally left testing logic in (@bcoe) - -### v3.5.0 (2015/03/09 04:49 +00:00) -- [718bacd](https://github.com/bcoe/yargs/commit/718bacd81b9b44f786af76b2afe491fe06274f19) added support for bash completions see #4 (@bcoe) -- [a192882](https://github.com/bcoe/yargs/commit/a19288270fc431396c42af01125eeb4443664528) downgrade to mocha 2.1.0 until https://github.com/mochajs/mocha/issues/1585 can be sorted out (@bcoe) - -### v3.4.7 (2015/03/09 04:09 +00:00) -- [9845e5c](https://github.com/bcoe/yargs/commit/9845e5c1a9c684ba0be3f0bfb40e7b62ab49d9c8) the Argv singleton was not being updated when manually parsing arguments, fixes #114 (@bcoe) - -### v3.4.6 (2015/03/09 04:01 +00:00) -- [45b4c80](https://github.com/bcoe/yargs/commit/45b4c80b890d02770b0a94f326695a8a566e8fe9) set placeholders for all keys fixes #115 (@bcoe) - -### v3.4.5 (2015/03/01 20:31 +00:00) -- [a758e0b](https://github.com/bcoe/yargs/commit/a758e0b2556184f067cf3d9c4ef886d39817ebd2) fix for count consuming too many arguments (@bcoe) - -### v3.4.4 (2015/02/28 04:52 +00:00) -- [0476af7](https://github.com/bcoe/yargs/commit/0476af757966acf980d998b45108221d4888cfcb) added nargs feature, allowing you to specify the number of arguments after an option (@bcoe) -- [092477d](https://github.com/bcoe/yargs/commit/092477d7ab3efbf0ba11cede57f7d8cfc70b024f) updated README with full example of v3.0 API (@bcoe) - -### v3.3.3 (2015/02/28 04:23 +00:00) -- [0c4b769](https://github.com/bcoe/yargs/commit/0c4b769516cd8d93a7c4e5e675628ae0049aa9a8) remove string dependency, which conflicted with other libraries see #106 (@bcoe) - -### v3.3.2 (2015/02/28 04:11 +00:00) -- [2a98906](https://github.com/bcoe/yargs/commit/2a9890675821c0e7a12f146ce008b0562cb8ec9a) add $0 to epilog (@schnittstabil) - -### v3.3.1 (2015/02/24 03:28 +00:00) -- [ad485ce](https://github.com/bcoe/yargs/commit/ad485ce748ebdfce25b88ef9d6e83d97a2f68987) fix for applying defaults to camel-case args (@bcoe) - -### v3.3.0 (2015/02/24 00:49 +00:00) -- [8bfe36d](https://github.com/bcoe/yargs/commit/8bfe36d7fb0f93a799ea3f4c756a7467c320f8c0) fix and document restart() command, as a tool for building nested CLIs (@bcoe) - -### v3.2.1 (2015/02/22 05:45 +00:00) -- [49a6d18](https://github.com/bcoe/yargs/commit/49a6d1822a4ef9b1ea6f90cc366be60912628885) you can now provide a function that generates a default value (@bcoe) - -### v3.2.0 (2015/02/22 05:24 +00:00) -- [7a55886](https://github.com/bcoe/yargs/commit/7a55886c9343cf71a20744ca5cdd56d2ea7412d5) improvements to yargs two-column text layout (@bcoe) -- [b6ab513](https://github.com/bcoe/yargs/commit/b6ab5136a4c3fa6aa496f6b6360382e403183989) Tweak NPM version badge (@nylen) - -### v3.1.0 (2015/02/19 19:37 +00:00) -- [9bd2379](https://github.com/bcoe/yargs/commit/9bd237921cf1b61fd9f32c0e6d23f572fc225861) version now accepts a function, making it easy to load version #s from a package.json (@bcoe) - -### v3.0.4 (2015/02/14 01:40 +00:00) -- [0b7c19b](https://github.com/bcoe/yargs/commit/0b7c19beaecb747267ca4cc10e5cb2a8550bc4b7) various fixes for dot-notation handling (@bcoe) - -### v3.0.3 (2015/02/14 00:59 +00:00) -- [c3f35e9](https://github.com/bcoe/yargs/commit/c3f35e99bd5a0d278073fcadd95e2d778616cc17) make sure dot-notation is applied to aliases (@bcoe) - -### 3.0.2 (2015/02/13 16:50 +00:00) -- [74c8967](https://github.com/bcoe/yargs/commit/74c8967c340c204a0a7edf8a702b6f46c2705435) document epilog shorthand of epilogue. (@bcoe) -- [670110f](https://github.com/bcoe/yargs/commit/670110fc01bedc4831b6fec6afac54517d5a71bc) any non-truthy value now causes check to fail see #76 (@bcoe) -- [0d8f791](https://github.com/bcoe/yargs/commit/0d8f791a33c11ced4cd431ea8d3d3a337d456b56) finished implementing my wish-list of fetures for yargs 3.0. see #88 (@bcoe) -- [5768447](https://github.com/bcoe/yargs/commit/5768447447c4c8e8304f178846206ce86540f063) fix coverage. (@bcoe) -- [82e793f](https://github.com/bcoe/yargs/commit/82e793f3f61c41259eaacb67f0796aea2cf2aaa0) detect console width and perform word-wrapping. (@bcoe) -- [67476b3](https://github.com/bcoe/yargs/commit/67476b37eea07fee55f23f35b9e0c7d76682b86d) refactor two-column table layout so that we can use it for examples and usage (@bcoe) -- [4724cdf](https://github.com/bcoe/yargs/commit/4724cdfcc8e37ae1ca3dcce9d762f476e9ef4bb4) major refactor of index.js, in prep for 3.x release. (@bcoe) - -### v2.3.0 (2015/02/08 20:41 +00:00) -- [d824620](https://github.com/bcoe/yargs/commit/d824620493df4e63664af1fe320764dd1a9244e6) allow for undefined boolean defaults (@ashi009) - -### v2.2.0 (2015/02/08 20:07 +00:00) -- [d6edd98](https://github.com/bcoe/yargs/commit/d6edd9848826e7389ed1393858c45d03961365fd) in-prep for further refactoring, and a 3.x release I've shuffled some things around and gotten test-coverage to 100%. (@bcoe) - -### v2.1.2 (2015/02/08 06:05 +00:00) -- [d640745](https://github.com/bcoe/yargs/commit/d640745a7b9f8d476e0223879d056d18d9c265c4) switch to path.relative (@bcoe) -- [3bfd41f](https://github.com/bcoe/yargs/commit/3bfd41ff262a041f29d828b88936a79c63cad594) remove mocha.opts. (@bcoe) -- [47a2f35](https://github.com/bcoe/yargs/commit/47a2f357091db70903a402d6765501c1d63f15fe) document using .string('_') for string ids. see #56 (@bcoe) -- [#57](https://github.com/bcoe/yargs/pull/57) Merge pull request #57 from eush77/option-readme (@eush77) - -### v2.1.1 (2015/02/06 08:08 +00:00) -- [01c6c61](https://github.com/bcoe/yargs/commit/01c6c61d67b4ebf88f41f0b32a345ec67f0ac17d) fix for #71, 'newAliases' of undefined (@bcoe) - -### v2.1.0 (2015/02/06 07:59 +00:00) -- [6a1a3fa](https://github.com/bcoe/yargs/commit/6a1a3fa731958e26ccd56885f183dd8985cc828f) try to guess argument types, and apply sensible defaults see #73 (@bcoe) - -### v2.0.1 (2015/02/06 07:54 +00:00) -- [96a06b2](https://github.com/bcoe/yargs/commit/96a06b2650ff1d085a52b7328d8bba614c20cc12) Fix for strange behavior with --sort option, see #51 (@bcoe) - -### v2.0.0 (2015/02/06 07:45 +00:00) -- [0250517](https://github.com/bcoe/yargs/commit/0250517c9643e53f431b824e8ccfa54937414011) - [108fb84](https://github.com/bcoe/yargs/commit/108fb8409a3a63dcaf99d917fe4dfcfaa1de236d) fixed bug with boolean parsing, when bools separated by = see #66 (@bcoe) -- [a465a59](https://github.com/bcoe/yargs/commit/a465a5915f912715738de890982e4f8395958b10) Add `files` field to the package.json (@shinnn) -- [31043de](https://github.com/bcoe/yargs/commit/31043de7a38a17c4c97711f1099f5fb164334db3) fix for yargs.argv having the same keys added multiple times see #63 (@bcoe) -- [2d68c5b](https://github.com/bcoe/yargs/commit/2d68c5b91c976431001c4863ce47c9297850f1ad) Disable process.exit calls using .exitProcess(false) (@cianclarke) -- [45da9ec](https://github.com/bcoe/yargs/commit/45da9ec4c55a7bd394721bc6a1db0dabad7bc52a) Mention .option in README (@eush77) - -### v1.3.2 (2014/10/06 21:56 +00:00) -- [b8d3472](https://github.com/bcoe/yargs/commit/b8d34725482e5821a3cc809c0df71378f282f526) 1.3.2 (@chevex) - -### list (2014/08/30 18:41 +00:00) -- [fbc777f](https://github.com/bcoe/yargs/commit/fbc777f416eeefd37c84e44d27d7dfc7c1925721) Now that yargs is the successor to optimist, I'm changing the README language to be more universal. Pirate speak isn't very accessible to non-native speakers. (@chevex) -- [a54d068](https://github.com/bcoe/yargs/commit/a54d0682ae2efc2394d407ab171cc8a8bbd135ea) version output will not print extra newline (@boneskull) -- [1cef5d6](https://github.com/bcoe/yargs/commit/1cef5d62a9d6d61a3948a49574892e01932cc6ae) Added contributors section to package.json (@chrisn) -- [cc295c0](https://github.com/bcoe/yargs/commit/cc295c0a80a2de267e0155b60d315fc4b6f7c709) Added 'require' and 'required' as synonyms for 'demand' (@chrisn) -- [d0bf951](https://github.com/bcoe/yargs/commit/d0bf951d949066b6280101ed606593d079ee15c8) Updating minimist. (@chevex) -- [c15f8e7](https://github.com/bcoe/yargs/commit/c15f8e7f245b261e542cf205ce4f4313630cbdb4) Fix #31 (bad interaction between camelCase options and strict mode) (@nylen) -- [d991b9b](https://github.com/bcoe/yargs/commit/d991b9be687a68812dee1e3b185ba64b7778b82d) Added .help() and .version() methods (@chrisn) -- [e8c8aa4](https://github.com/bcoe/yargs/commit/e8c8aa46268379357cb11e9fc34b8c403037724b) Added .showHelpOnFail() method (@chrisn) -- [e855af4](https://github.com/bcoe/yargs/commit/e855af4a933ea966b5bbdd3c4c6397a4bac1a053) Allow boolean flag with .demand() (@chrisn) -- [14dbec2](https://github.com/bcoe/yargs/commit/14dbec24fb7380683198e2b20c4deb8423e64bea) Fixes issue #22. Arguments are no longer printed to the console when using .config. (@chevex) -- [bef74fc](https://github.com/bcoe/yargs/commit/bef74fcddc1544598a804f80d0a3728459f196bf) Informing users that Yargs is the official optimist successor. (@chevex) -- [#24](https://github.com/bcoe/yargs/pull/24) Merge pull request #24 from chrisn/strict (@chrisn) -- [889a2b2](https://github.com/bcoe/yargs/commit/889a2b28eb9768801b05163360a470d0fd6c8b79) Added requiresArg option, for options that require values (@chrisn) -- [eb16369](https://github.com/bcoe/yargs/commit/eb163692262be1fe80b992fd8803d5923c5a9b18) Added .strict() method, to report error if unknown arguments are given (@chrisn) -- [0471c3f](https://github.com/bcoe/yargs/commit/0471c3fd999e1ad4e6cded88b8aa02013b66d14f) Changed optimist to yargs in usage-options.js example (@chrisn) -- [5c88f74](https://github.com/bcoe/yargs/commit/5c88f74e3cf031b17c54b4b6606c83e485ff520e) Change optimist to yargs in examples (@chrisn) -- [66f12c8](https://github.com/bcoe/yargs/commit/66f12c82ba3c943e4de8ca862980e835da8ecb3a) Fix a couple of bad interactions between aliases and defaults (@nylen) -- [8fa1d80](https://github.com/bcoe/yargs/commit/8fa1d80f14b03eb1f2898863a61f1d1615bceb50) Document second argument of usage(message, opts) (@Gobie) -- [56e6528](https://github.com/bcoe/yargs/commit/56e6528cf674ff70d63083fb044ff240f608448e) For "--some-option", also set argv.someOption (@nylen) -- [ed5f6d3](https://github.com/bcoe/yargs/commit/ed5f6d33f57ad1086b11c91b51100f7c6c7fa8ee) Finished porting unit tests to Mocha. (@chevex) - -### v1.0.15 (2014/02/05 23:18 +00:00) -- [e2b1fc0](https://github.com/bcoe/yargs/commit/e2b1fc0c4a59cf532ae9b01b275e1ef57eeb64d2) 1.0.15 update to badges (@chevex) - -### v1.0.14 (2014/02/05 23:17 +00:00) -- [f33bbb0](https://github.com/bcoe/yargs/commit/f33bbb0f00fe18960f849cc8e15a7428a4cd59b8) Revert "Fixed issue which caused .demand function not to work correctly." (@chevex) - -### v1.0.13 (2014/02/05 22:13 +00:00) -- [6509e5e](https://github.com/bcoe/yargs/commit/6509e5e7dee6ef1a1f60eea104be0faa1a045075) Fixed issue which caused .demand function not to work correctly. (@chevex) - -### v1.0.12 (2013/12/13 00:09 +00:00) -- [05eb267](https://github.com/bcoe/yargs/commit/05eb26741c9ce446b33ff006e5d33221f53eaceb) 1.0.12 (@chevex) - -### v1.0.11 (2013/12/13 00:07 +00:00) -- [c1bde46](https://github.com/bcoe/yargs/commit/c1bde46e37318a68b87d17a50c130c861d6ce4a9) 1.0.11 (@chevex) - -### v1.0.10 (2013/12/12 23:57 +00:00) -- [dfebf81](https://github.com/bcoe/yargs/commit/dfebf8164c25c650701528ee581ca483a99dc21c) Fixed formatting in README (@chevex) - -### v1.0.9 (2013/12/12 23:47 +00:00) -- [0b4e34a](https://github.com/bcoe/yargs/commit/0b4e34af5e6d84a9dbb3bb6d02cd87588031c182) Update README.md (@chevex) - -### v1.0.8 (2013/12/06 16:36 +00:00) -- [#1](https://github.com/bcoe/yargs/pull/1) fix error caused by check() see #1 (@martinheidegger) - -### v1.0.7 (2013/11/24 18:01 +00:00) -- [a247d88](https://github.com/bcoe/yargs/commit/a247d88d6e46644cbb7303c18b1bb678fc132d72) Modified Pirate Joe image. (@chevex) - -### v1.0.6 (2013/11/23 19:21 +00:00) -- [d7f69e1](https://github.com/bcoe/yargs/commit/d7f69e1d34bc929736a8bdccdc724583e21b7eab) Updated Pirate Joe image. (@chevex) - -### v1.0.5 (2013/11/23 19:09 +00:00) -- [ece809c](https://github.com/bcoe/yargs/commit/ece809cf317cc659175e1d66d87f3ca68c2760be) Updated readme notice again. (@chevex) - -### v1.0.4 (2013/11/23 19:05 +00:00) -- [9e81e81](https://github.com/bcoe/yargs/commit/9e81e81654028f83ba86ffc3ac772a0476084e5e) Updated README with a notice about yargs being a fork of optimist and what that implies. (@chevex) - -### v1.0.3 (2013/11/23 17:43 +00:00) -- [65e7a78](https://github.com/bcoe/yargs/commit/65e7a782c86764944d63d084416aba9ee6019c5f) Changed some small wording in README.md. (@chevex) -- [459e20e](https://github.com/bcoe/yargs/commit/459e20e539b366b85128dd281ccd42221e96c7da) Fix a bug in the options function, when string and boolean options weren't applied to aliases. (@shockone) - -### v1.0.2 (2013/11/23 09:46 +00:00) -- [3d80ebe](https://github.com/bcoe/yargs/commit/3d80ebed866d3799224b6f7d596247186a3898a9) 1.0.2 (@chevex) - -### v1.0.1 (2013/11/23 09:39 +00:00) -- [f80ff36](https://github.com/bcoe/yargs/commit/f80ff3642d580d4b68bf9f5a94277481bd027142) Updated image. (@chevex) - -### v1.0.0 (2013/11/23 09:33 +00:00) -- [54e31d5](https://github.com/bcoe/yargs/commit/54e31d505f820b80af13644e460894b320bf25a3) Rebranded from optimist to yargs in the spirit of the fork :D (@chevex) -- [4ebb6c5](https://github.com/bcoe/yargs/commit/4ebb6c59f44787db7c24c5b8fe2680f01a23f498) Added documentation for demandCount(). (@chevex) -- [4561ce6](https://github.com/bcoe/yargs/commit/4561ce66dcffa95f49e8b4449b25b94cd68acb25) Simplified the error messages returned by .check(). (@chevex) -- [661c678](https://github.com/bcoe/yargs/commit/661c67886f479b16254a830b7e1db3be29e6b7a6) Fixed an issue with demand not accepting a zero value. (@chevex) -- [731dd3c](https://github.com/bcoe/yargs/commit/731dd3c37624790490bd6df4d5f1da8f4348279e) Add .fail(fn) so death isn't the only option. Should fix issue #39. (@chevex) -- [fa15417](https://github.com/bcoe/yargs/commit/fa15417ff9e70dace0d726627a5818654824c1d8) Added a few missing 'return self' (@chevex) -- [e655e4d](https://github.com/bcoe/yargs/commit/e655e4d99d1ae1d3695ef755d51c2de08d669761) Fix showing help in certain JS environments. (@chevex) -- [a746a31](https://github.com/bcoe/yargs/commit/a746a31cd47c87327028e6ea33762d6187ec5c87) Better string representation of default values. (@chevex) -- [6134619](https://github.com/bcoe/yargs/commit/6134619a7e90b911d5443230b644c5d447c1a68c) Implies: conditional demands (@chevex) -- [046b93b](https://github.com/bcoe/yargs/commit/046b93b5d40a27367af4cb29726e4d781d934639) Added support for JSON config files. (@chevex) -- [a677ec0](https://github.com/bcoe/yargs/commit/a677ec0a0ecccd99c75e571d03323f950688da03) Add .example(cmd, desc) feature. (@chevex) -- [1bd4375](https://github.com/bcoe/yargs/commit/1bd4375e11327ba1687d4bb6e5e9f3c30c1be2af) Added 'defaults' as alias to 'default' so as to avoid usage of a reserved keyword. (@chevex) -- [6b753c1](https://github.com/bcoe/yargs/commit/6b753c16ca09e723060e70b773b430323b29c45c) add .normalize(args..) support for normalizing paths (@chevex) -- [33d7d59](https://github.com/bcoe/yargs/commit/33d7d59341d364f03d3a25f0a55cb99004dbbe4b) Customize error messages with demand(key, msg) (@chevex) -- [647d37f](https://github.com/bcoe/yargs/commit/647d37f164c20f4bafbf67dd9db6cd6e2cd3b49f) Merge branch 'rewrite-duplicate-test' of github.com:isbadawi/node-optimist (@chevex) -- [9059d1a](https://github.com/bcoe/yargs/commit/9059d1ad5e8aea686c2a01c89a23efdf929fff2e) Pass aliases object to check functions for greater versatility. (@chevex) -- [623dc26](https://github.com/bcoe/yargs/commit/623dc26c7331abff2465ef8532e3418996d42fe6) Added ability to count boolean options and rolled minimist library back into project. (@chevex) -- [49f0dce](https://github.com/bcoe/yargs/commit/49f0dcef35de4db544c3966350d36eb5838703f6) Fixed small typo. (@chevex) -- [79ec980](https://github.com/bcoe/yargs/commit/79ec9806d9ca6eb0014cfa4b6d1849f4f004baf2) Removed dependency on wordwrap module. (@chevex) -- [ea14630](https://github.com/bcoe/yargs/commit/ea14630feddd69d1de99dd8c0e08948f4c91f00a) Merge branch 'master' of github.com:chbrown/node-optimist (@chevex) -- [2b75da2](https://github.com/bcoe/yargs/commit/2b75da2624061e0f4f3107d20303c06ec9054906) Merge branch 'master' of github.com:seanzhou1023/node-optimist (@chevex) -- [d9bda11](https://github.com/bcoe/yargs/commit/d9bda1116e26f3b40e833ca9ca19263afea53565) Merge branch 'patch-1' of github.com:thefourtheye/node-optimist (@chevex) -- [d6cc606](https://github.com/bcoe/yargs/commit/d6cc6064a4f1bea38a16a4430b8a1334832fbeff) Renamed README. (@chevex) -- [9498d3f](https://github.com/bcoe/yargs/commit/9498d3f59acfb5e102826503e681623c3a64b178) Renamed readme and added .gitignore. (@chevex) -- [bbd1fe3](https://github.com/bcoe/yargs/commit/bbd1fe37fefa366dde0fb3dc44d91fe8b28f57f5) Included examples for ```help``` and ```showHelp``` functions and fixed few formatting issues (@thefourtheye) -- [37fea04](https://github.com/bcoe/yargs/commit/37fea0470a5796a0294c1dcfff68d8041650e622) .alias({}) behaves differently based on mapping direction when generating descriptions (@chbrown) -- [855b20d](https://github.com/bcoe/yargs/commit/855b20d0be567ca121d06b30bea64001b74f3d6d) Documented function signatures are useful for dynamically typed languages. (@chbrown) - -### 0.6.0 (2013/06/25 08:48 +00:00) -- [d37bfe0](https://github.com/bcoe/yargs/commit/d37bfe05ae6d295a0ab481efe4881222412791f4) all tests passing using minimist (@substack) -- [76f1352](https://github.com/bcoe/yargs/commit/76f135270399d01f2bbc621e524a5966e5c422fd) all parse tests now passing (@substack) -- [a7b6754](https://github.com/bcoe/yargs/commit/a7b6754276c38d1565479a5685c3781aeb947816) using minimist, some tests passing (@substack) -- [6655688](https://github.com/bcoe/yargs/commit/66556882aa731cbbbe16cc4d42c85740a2e98099) Give credit where its due (@DeadAlready) -- [602a2a9](https://github.com/bcoe/yargs/commit/602a2a92a459f93704794ad51b115bbb08b535ce) v0.5.3 - Remove wordwrap as dependency (@DeadAlready) - -### 0.5.2 (2013/05/31 03:46 +00:00) -- [4497ca5](https://github.com/bcoe/yargs/commit/4497ca55e332760a37b866ec119ded347ca27a87) fixed the whitespace bug without breaking anything else (@substack) -- [5a3dd1a](https://github.com/bcoe/yargs/commit/5a3dd1a4e0211a38613c6e02f61328e1031953fa) failing test for whitespace arg (@substack) - -### 0.5.1 (2013/05/30 07:17 +00:00) -- [a20228f](https://github.com/bcoe/yargs/commit/a20228f62a454755dd07f628a7c5759113918327) fix parse() to work with functions before it (@substack) -- [b13bd4c](https://github.com/bcoe/yargs/commit/b13bd4cac856a9821d42fa173bdb58f089365a7d) failing test for parse() with modifiers (@substack) - -### 0.5.0 (2013/05/18 21:59 +00:00) -- [c474a64](https://github.com/bcoe/yargs/commit/c474a649231527915c222156e3b40806d365a87c) fixes for dash (@substack) - -### 0.4.0 (2013/04/13 19:03 +00:00) -- [dafe3e1](https://github.com/bcoe/yargs/commit/dafe3e18d7c6e7c2d68e06559df0e5cbea3adb14) failing short test (@substack) - -### 0.3.7 (2013/04/04 04:07 +00:00) -- [6c7a0ec](https://github.com/bcoe/yargs/commit/6c7a0ec94ce4199a505f0518b4d6635d4e47cc81) Fix for windows. On windows there is no _ in environment. (@hdf) - -### 0.3.6 (2013/04/04 04:04 +00:00) -- [e72346a](https://github.com/bcoe/yargs/commit/e72346a727b7267af5aa008b418db89970873f05) Add support for newlines in -a="" arguments (@danielbeardsley) -- [71e1fb5](https://github.com/bcoe/yargs/commit/71e1fb55ea9987110a669ac6ec12338cfff3821c) drop 0.4, add 0.8 to travis (@substack) - -### 0.3.5 (2012/10/10 11:09 +00:00) -- [ee692b3](https://github.com/bcoe/yargs/commit/ee692b37554c70a0bb16389a50a26b66745cbbea) Fix parsing booleans (@vojtajina) -- [5045122](https://github.com/bcoe/yargs/commit/5045122664c3f5b4805addf1be2148d5856f7ce8) set $0 properly in the tests (@substack) - -### 0.3.4 (2012/04/30 06:54 +00:00) -- [f28c0e6](https://github.com/bcoe/yargs/commit/f28c0e62ca94f6e0bb2e6d82fc3d91a55e69b903) bump for string "true" params (@substack) -- [8f44aeb](https://github.com/bcoe/yargs/commit/8f44aeb74121ddd689580e2bf74ef86a605e9bf2) Fix failing test for aliased booleans. (@coderarity) -- [b9f7b61](https://github.com/bcoe/yargs/commit/b9f7b613b1e68e11e6c23fbda9e555a517dcc976) Add failing test for short aliased booleans. (@coderarity) - -### 0.3.3 (2012/04/30 06:45 +00:00) -- [541bac8](https://github.com/bcoe/yargs/commit/541bac8dd787a5f1a5d28f6d8deb1627871705e7) Fixes #37. - -### 0.3.2 (2012/04/12 20:28 +00:00) -- [3a0f014](https://github.com/bcoe/yargs/commit/3a0f014c1451280ac1c9caa1f639d31675586eec) travis badge (@substack) -- [4fb60bf](https://github.com/bcoe/yargs/commit/4fb60bf17845f4ce3293f8ca49c9a1a7c736cfce) Fix boolean aliases. (@coderarity) -- [f14dda5](https://github.com/bcoe/yargs/commit/f14dda546efc4fe06ace04d36919bfbb7634f79b) Adjusted package.json to use tap (@jfhbrook) -- [88e5d32](https://github.com/bcoe/yargs/commit/88e5d32295be6e544c8d355ff84e355af38a1c74) test/usage.js no longer hangs (@jfhbrook) -- [e1e740c](https://github.com/bcoe/yargs/commit/e1e740c27082f3ce84deca2093d9db2ef735d0e5) two tests for combined boolean/alias opts parsing (@jfhbrook) - -### 0.3.1 (2011/12/31 08:44 +00:00) -- [d09b719](https://github.com/bcoe/yargs/commit/d09b71980ef711b6cf3918cd19beec8257e40e82) If "default" is set to false it was not passed on, fixed. (@wolframkriesing) - -### 0.3.0 (2011/12/09 06:03 +00:00) -- [6e74aa7](https://github.com/bcoe/yargs/commit/6e74aa7b46a65773e20c0cb68d2d336d4a0d553d) bump and documented dot notation (@substack) - -### 0.2.7 (2011/10/20 02:25 +00:00) -- [94adee2](https://github.com/bcoe/yargs/commit/94adee20e17b58d0836f80e8b9cdbe9813800916) argv._ can be told 'Hey! argv._! Don't be messing with my args.', and it WILL obey (@colinta) -- [c46fdd5](https://github.com/bcoe/yargs/commit/c46fdd56a05410ae4a1e724a4820c82e77ff5469) optimistic critter image (@substack) -- [5c95c73](https://github.com/bcoe/yargs/commit/5c95c73aedf4c7482bd423e10c545e86d7c8a125) alias options() to option() (@substack) -- [f7692ea](https://github.com/bcoe/yargs/commit/f7692ea8da342850af819367833abb685fde41d8) [fix] Fix for parsing boolean edge case (@indexzero) -- [d1f92d1](https://github.com/bcoe/yargs/commit/d1f92d1425bd7f356055e78621b30cdf9741a3c2) -- [b01bda8](https://github.com/bcoe/yargs/commit/b01bda8d86e455bbf74ce497864cb8ab5b9fb847) [fix test] Update to ensure optimist is aware of default booleans. Associated tests included (@indexzero) -- [aa753e7](https://github.com/bcoe/yargs/commit/aa753e7c54fb3a12f513769a0ff6d54aa0f63943) [dist test] Update devDependencies in package.json. Update test pathing to be more npm and require.paths future-proof (@indexzero) -- [7bfce2f](https://github.com/bcoe/yargs/commit/7bfce2f3b3c98e6539e7549d35fbabced7e9341e) s/sys/util/ (@substack) -- [d420a7a](https://github.com/bcoe/yargs/commit/d420a7a9c890d2cdb11acfaf3ea3f43bc3e39f41) update usage output (@substack) -- [cf86eed](https://github.com/bcoe/yargs/commit/cf86eede2e5fc7495b6ec15e6d137d9ac814f075) some sage readme protips about parsing rules (@substack) -- [5da9f7a](https://github.com/bcoe/yargs/commit/5da9f7a5c0e1758ec7c5801fb3e94d3f6e970513) documented all the methods finally (@substack) -- [8ca6879](https://github.com/bcoe/yargs/commit/8ca6879311224b25933642987300f6a29de5c21b) fenced syntax highlighting (@substack) -- [b72bacf](https://github.com/bcoe/yargs/commit/b72bacf1d02594778c1935405bc8137eb61761dc) right-alignment of wrapped extra params (@substack) -- [2b980bf](https://github.com/bcoe/yargs/commit/2b980bf2656b4ee8fc5134dc5f56a48855c35198) now with .wrap() (@substack) -- [d614f63](https://github.com/bcoe/yargs/commit/d614f639654057d1b7e35e3f5a306e88ec2ad1e4) don't show 'Options:' when there aren't any (@substack) -- [691eda3](https://github.com/bcoe/yargs/commit/691eda354df97b5a86168317abcbcaabdc08a0fb) failing test for multi-aliasing (@substack) -- [0826c9f](https://github.com/bcoe/yargs/commit/0826c9f462109feab2bc7a99346d22e72bf774b7) "Options:" > "options:" (@substack) -- [72f7490](https://github.com/bcoe/yargs/commit/72f749025d01b7f295738ed370a669d885fbada0) [minor] Update formatting for `.showHelp()` (@indexzero) -- [75aecce](https://github.com/bcoe/yargs/commit/75aeccea74329094072f95800e02c275e7d999aa) options works again, too lazy to write a proper test right now (@substack) -- [f742e54](https://github.com/bcoe/yargs/commit/f742e5439817c662dc3bd8734ddd6467e6018cfd) line_count_options example, which breaks (@substack) -- [4ca06b8](https://github.com/bcoe/yargs/commit/4ca06b8b4ea99b5d5714b315a2a8576bee6e5537) line count example (@substack) -- [eeb8423](https://github.com/bcoe/yargs/commit/eeb8423e0a5ecc9dc3eb1e6df9f3f8c1c88f920b) remove self.argv setting in boolean (@substack) -- [6903412](https://github.com/bcoe/yargs/commit/69034126804660af9cc20ea7f4457b50338ee3d7) removed camel case for now (@substack) -- [5a0d88b](https://github.com/bcoe/yargs/commit/5a0d88bf23e9fa79635dd034e2a1aa992acc83cd) remove dead longest checking code (@substack) -- [d782170](https://github.com/bcoe/yargs/commit/d782170babf7284b1aa34f5350df0dd49c373fa8) .help() too (@substack) -- [622ec17](https://github.com/bcoe/yargs/commit/622ec17379bb5374fdbb190404c82bc600975791) rm old help generator (@substack) -- [7c8baac](https://github.com/bcoe/yargs/commit/7c8baac4d66195e9f5158503ea9ebfb61153dab7) nub keys (@substack) -- [8197785](https://github.com/bcoe/yargs/commit/8197785ad4762465084485b041abd722f69bf344) generate help message based on the previous calls, todo: nub (@substack) -- [3ffbdc3](https://github.com/bcoe/yargs/commit/3ffbdc33c8f5e83d4ea2ac60575ce119570c7ede) stub out new showHelp, better checks (@substack) -- [d4e21f5](https://github.com/bcoe/yargs/commit/d4e21f56a4830f7de841900d3c79756fb9886184) let .options() take single options too (@substack) -- [3c4cf29](https://github.com/bcoe/yargs/commit/3c4cf2901a29bac119cca8e983028d8669230ec6) .options() is now heaps simpler (@substack) -- [89f0d04](https://github.com/bcoe/yargs/commit/89f0d043cbccd302f10ab30c2069e05d2bf817c9) defaults work again, all tests pass (@substack) -- [dd87333](https://github.com/bcoe/yargs/commit/dd8733365423006a6e4156372ebb55f98323af58) update test error messages, down to 2 failing tests (@substack) -- [53f7bc6](https://github.com/bcoe/yargs/commit/53f7bc626b9875f2abdfc5dd7a80bde7f14143a3) fix for bools doubling up, passes the parse test again, others fail (@substack) -- [2213e2d](https://github.com/bcoe/yargs/commit/2213e2ddc7263226fba717fb041dc3fde9bc2ee4) refactored for an argv getter, failing several tests (@substack) -- [d1e7379](https://github.com/bcoe/yargs/commit/d1e737970f15c6c006bebdd8917706827ff2f0f2) just rescan for now, alias test passes (@substack) -- [b2f8c99](https://github.com/bcoe/yargs/commit/b2f8c99cc477a8eb0fdf4cf178e1785b63185cfd) failing alias test (@substack) -- [d0c0174](https://github.com/bcoe/yargs/commit/d0c0174daa144bfb6dc7290fdc448c393c475e15) .alias() (@substack) -- [d85f431](https://github.com/bcoe/yargs/commit/d85f431ad7d07b058af3f2a57daa51495576c164) [api] Remove `.describe()` in favor of building upon the existing `.usage()` API (@indexzero) -- [edbd527](https://github.com/bcoe/yargs/commit/edbd5272a8e213e71acd802782135c7f9699913a) [doc api] Add `.describe()`, `.options()`, and `.showHelp()` methods along with example. (@indexzero) -- [be4902f](https://github.com/bcoe/yargs/commit/be4902ff0961ae8feb9093f2c0a4066463ded2cf) updates for coffee since it now does argv the node way (@substack) -- [e24cb23](https://github.com/bcoe/yargs/commit/e24cb23798ee64e53b60815e7fda78b87f42390c) more general coffeescript detection (@substack) -- [78ac753](https://github.com/bcoe/yargs/commit/78ac753e5d0ec32a96d39d893272afe989e42a4d) Don't trigger the CoffeeScript hack when running under node_g. (@papandreou) -- [bcfe973](https://github.com/bcoe/yargs/commit/bcfe9731d7f90d4632281b8a52e8d76eb0195ae6) .string() but failing test (@substack) -- [1987aca](https://github.com/bcoe/yargs/commit/1987aca28c7ba4e8796c07bbc547cb984804c826) test hex strings (@substack) -- [ef36db3](https://github.com/bcoe/yargs/commit/ef36db32259b0b0d62448dc907c760e5554fb7e7) more keywords (@substack) -- [cc53c56](https://github.com/bcoe/yargs/commit/cc53c56329960bed6ab077a79798e991711ba01d) Added camelCase function that converts --multi-word-option to camel case (so it becomes argv.multiWordOption). (@papandreou) -- [60b57da](https://github.com/bcoe/yargs/commit/60b57da36797716e5783a633c6d5c79099016d45) fixed boolean bug by rescanning (@substack) -- [dff6d07](https://github.com/bcoe/yargs/commit/dff6d078d97f8ac503c7d18dcc7b7a8c364c2883) boolean examples (@substack) -- [0e380b9](https://github.com/bcoe/yargs/commit/0e380b92c4ef4e3c8dac1da18b5c31d85b1d02c9) boolean() with passing test (@substack) -- [62644d4](https://github.com/bcoe/yargs/commit/62644d4bffbb8d1bbf0c2baf58a1d14a6359ef07) coffee compatibility with node regex for versions too (@substack) -- [430fafc](https://github.com/bcoe/yargs/commit/430fafcf1683d23774772826581acff84b456827) argv._ fixed by fixing the coffee detection (@substack) -- [343b8af](https://github.com/bcoe/yargs/commit/343b8afefd98af274ebe21b5a16b3a949ec5429f) whichNodeArgs test fails too (@substack) -- [63df2f3](https://github.com/bcoe/yargs/commit/63df2f371f31e63d7f1dec2cbf0022a5f08da9d2) replicated mnot's bug in whichNodeEmpty test (@substack) -- [35473a4](https://github.com/bcoe/yargs/commit/35473a4d93a45e5e7e512af8bb54ebb532997ae1) test for ./bin usage (@substack) -- [13df151](https://github.com/bcoe/yargs/commit/13df151e44228eed10e5441c7cd163e086c458a4) don't coerce booleans to numbers (@substack) -- [85f8007](https://github.com/bcoe/yargs/commit/85f8007e93b8be7124feea64b1f1916d8ba1894a) package bump for automatic number conversion (@substack) -- [8f17014](https://github.com/bcoe/yargs/commit/8f170141cded4ccc0c6d67a849c5bf996aa29643) updated readme and examples with new auto-numberification goodness (@substack) -- [73dc901](https://github.com/bcoe/yargs/commit/73dc9011ac968e39b55e19e916084a839391b506) auto number conversion works yay (@substack) -- [bcec56b](https://github.com/bcoe/yargs/commit/bcec56b3d031e018064cbb691539ccc4f28c14ad) failing test for not-implemented auto numification (@substack) -- [ebd2844](https://github.com/bcoe/yargs/commit/ebd2844d683feeac583df79af0e5124a7a7db04e) odd that eql doesn't check types careflly (@substack) -- [fd854b0](https://github.com/bcoe/yargs/commit/fd854b02e512ce854b76386d395672a7969c1bc4) package author + keywords (@substack) -- [656a1d5](https://github.com/bcoe/yargs/commit/656a1d5a1b7c0e49d72e80cb13f20671d56f76c6) updated readme with .default() stuff (@substack) -- [cd7f8c5](https://github.com/bcoe/yargs/commit/cd7f8c55f0b82b79b690d14c5f806851236998a1) passing tests for new .default() behavior (@substack) -- [932725e](https://github.com/bcoe/yargs/commit/932725e39ce65bc91a0385a5fab659a5fa976ac2) new default() thing for setting default key/values (@substack) -- [4e6c7ab](https://github.com/bcoe/yargs/commit/4e6c7aba6374ac9ebc6259ecf91f13af7bce40e3) test for coffee usage (@substack) -- [d54ffcc](https://github.com/bcoe/yargs/commit/d54ffccf2a5a905f51ed5108f7c647f35d64ae23) new --key value style with passing tests. NOTE: changes existing behavior (@substack) -- [ed2a2d5](https://github.com/bcoe/yargs/commit/ed2a2d5d828100ebeef6385c0fb88d146a5cfe9b) package bump for summatix's coffee script fix (@substack) -- [75a975e](https://github.com/bcoe/yargs/commit/75a975eed8430d28e2a79dc9e6d819ad545f4587) Added support for CoffeeScript (@summatix) -- [56b2b1d](https://github.com/bcoe/yargs/commit/56b2b1de8d11f8a2b91979d8ae2d6db02d8fe64d) test coverage for the falsy check() usage (@substack) -- [a4843a9](https://github.com/bcoe/yargs/commit/a4843a9f0e69ffb4afdf6a671d89eb6f218be35d) check bug fixed plus a handy string (@substack) -- [857bd2d](https://github.com/bcoe/yargs/commit/857bd2db933a5aaa9cfecba0ced2dc9b415f8111) tests for demandCount, back up to 100% coverage (@substack) -- [073b776](https://github.com/bcoe/yargs/commit/073b7768ebd781668ef05c13f9003aceca2f5c35) call demandCount from demand (@substack) -- [4bd4b7a](https://github.com/bcoe/yargs/commit/4bd4b7a085c8b6ce1d885a0f486cc9865cee2db1) add demandCount to check for the number of arguments in the _ list (@marshall) -- [b8689ac](https://github.com/bcoe/yargs/commit/b8689ac68dacf248119d242bba39a41cb0adfa07) Rebase checks. That will be its own module eventually. (@substack) -- [e688370](https://github.com/bcoe/yargs/commit/e688370b576f0aa733c3f46183df69e1b561668e) a $0 like in perl (@substack) -- [2e5e196](https://github.com/bcoe/yargs/commit/2e5e1960fc19afb21fb3293752316eaa8bcd3609) usage test hacking around process and console (@substack) -- [fcc3521](https://github.com/bcoe/yargs/commit/fcc352163fbec6a1dfe8caf47a0df39de24fe016) description pun (@substack) -- [87a1fe2](https://github.com/bcoe/yargs/commit/87a1fe29037ca2ca5fefda85141aaeb13e8ce761) mit/x11 license (@substack) -- [8d089d2](https://github.com/bcoe/yargs/commit/8d089d24cd687c0bde3640a96c09b78f884900dd) bool example is more consistent and also shows off short option grouping (@substack) -- [448d747](https://github.com/bcoe/yargs/commit/448d7473ac68e8e03d8befc9457b0d9e21725be0) start of the readme and examples (@substack) -- [da74dea](https://github.com/bcoe/yargs/commit/da74dea799a9b59dbf022cbb8001bfdb0d52eec9) more tests for long and short captures (@substack) -- [ab6387e](https://github.com/bcoe/yargs/commit/ab6387e6769ca4af82ca94c4c67c7319f0d9fcfa) silly bug in the tests with s/not/no/, all tests pass now (@substack) -- [102496a](https://github.com/bcoe/yargs/commit/102496a319e8e06f6550d828fc2f72992c7d9ecc) hack an instance for process.argv onto Argv so the export can be called to create an instance or used for argv, which is the most common case (@substack) -- [a01caeb](https://github.com/bcoe/yargs/commit/a01caeb532546d19f68f2b2b87f7036cfe1aaedd) divide example (@substack) -- [443da55](https://github.com/bcoe/yargs/commit/443da55736acbaf8ff8b04d1b9ce19ab016ddda2) start of the lib with a package.json (@substack) diff --git a/node_modules/webpack/node_modules/yargs/LICENSE b/node_modules/webpack/node_modules/yargs/LICENSE deleted file mode 100644 index 747ab114c..000000000 --- a/node_modules/webpack/node_modules/yargs/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -Copyright 2010 James Halliday (mail@substack.net) -Modified work Copyright 2014 Contributors (ben@npmjs.com) - -This project is free software released under the MIT/X11 license: - -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. diff --git a/node_modules/webpack/node_modules/yargs/README.md b/node_modules/webpack/node_modules/yargs/README.md deleted file mode 100644 index 867118bfe..000000000 --- a/node_modules/webpack/node_modules/yargs/README.md +++ /dev/null @@ -1,103 +0,0 @@ -# Yargs - -[![Build Status][travis-image]][travis-url] -[![Coverage Status][coveralls-image]][coveralls-url] -[![NPM version][npm-image]][npm-url] -[![Windows Tests][windows-image]][windows-url] -[![js-standard-style][standard-image]][standard-url] -[![Conventional Commits][conventional-commits-image]][conventional-commits-url] -[![Gitter][gitter-image]][gitter-url] - -> Yargs be a node.js library fer hearties tryin' ter parse optstrings. - -<img width="250" src="/yargs-logo.png"> - -Yargs helps you build interactive command line tools, by parsing arguments and generating an elegant user interface. It gives you: - -* commands and (grouped) options (`my-program.js serve --port=5000`). -* a dynamically generated help menu based on your arguments. - -> <img width="400" src="/screen.png"> - -* bash-completion shortcuts for commands and options. -* and [tons more](/docs/api.md). - -## Installation - -```bash -npm i yargs --save -``` - -## Simple Example - -````javascript -#!/usr/bin/env node -const argv = require('yargs').argv - -if (argv.ships > 3 && argv.distance < 53.5) { - console.log('Plunder more riffiwobbles!') -} else { - console.log('Retreat from the xupptumblers!') -} -```` - -```bash -$ ./plunder.js --ships=4 --distance=22 -Plunder more riffiwobbles! - -$ ./plunder.js --ships 12 --distance 98.7 -Retreat from the xupptumblers! -``` - -## Complex Example - -```js -#!/usr/bin/env node -const yargs = require('yargs') // eslint-disable-line - .command('serve', 'start the server', (yargs) => { - yargs.option('port', { - describe: 'port to bind on', - default: 5000 - }) - }, (argv) => { - if (argv.verbose) console.info(`start server on :${argv.port}`) - serve(argv.port) - }) - .option('verbose', { - alias: 'v', - default: false - }) - .help() - .argv -``` - -## Table of Contents - -* [Yargs' API](/docs/api.md) -* [Examples](/docs/examples.md) -* [Parsing Tricks](/docs/tricks.md) - * [Stop the Parser](/docs/tricks.md#stop) - * [Negating Boolean Arguments](/docs/tricks.md#negate) - * [Numbers](/docs/tricks.md#numbers) - * [Arrays](/docs/tricks.md#arrays) - * [Objects](/docs/tricks.md#objects) -* [Advanced Topics](/docs/advanced.md) - * [Composing Your App Using Commands](/docs/advanced.md#commands) - * [Building Configurable CLI Apps](/docs/advanced.md#configuration) - * [Customizing Yargs' Parser](/docs/advanced.md#customizing) -* [Contributing](/contributing.md) - -[travis-url]: https://travis-ci.org/yargs/yargs -[travis-image]: https://img.shields.io/travis/yargs/yargs/master.svg -[coveralls-url]: https://coveralls.io/github/yargs/yargs -[coveralls-image]: https://img.shields.io/coveralls/yargs/yargs.svg -[npm-url]: https://www.npmjs.com/package/yargs -[npm-image]: https://img.shields.io/npm/v/yargs.svg -[windows-url]: https://ci.appveyor.com/project/bcoe/yargs-ljwvf -[windows-image]: https://img.shields.io/appveyor/ci/bcoe/yargs-ljwvf/master.svg?label=Windows%20Tests -[standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg -[standard-url]: http://standardjs.com/ -[conventional-commits-image]: https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg -[conventional-commits-url]: https://conventionalcommits.org/ -[gitter-image]: https://img.shields.io/gitter/room/nwjs/nw.js.svg?maxAge=2592000 -[gitter-url]: https://gitter.im/yargs/Lobby?utm_source=share-link&utm_medium=link&utm_campaign=share-link diff --git a/node_modules/webpack/node_modules/yargs/completion.sh.hbs b/node_modules/webpack/node_modules/yargs/completion.sh.hbs deleted file mode 100644 index 14445b834..000000000 --- a/node_modules/webpack/node_modules/yargs/completion.sh.hbs +++ /dev/null @@ -1,28 +0,0 @@ -###-begin-{{app_name}}-completions-### -# -# yargs command completion script -# -# Installation: {{app_path}} completion >> ~/.bashrc -# or {{app_path}} completion >> ~/.bash_profile on OSX. -# -_yargs_completions() -{ - local cur_word args type_list - - cur_word="${COMP_WORDS[COMP_CWORD]}" - args=("${COMP_WORDS[@]}") - - # ask yargs to generate completions. - type_list=$({{app_path}} --get-yargs-completions "${args[@]}") - - COMPREPLY=( $(compgen -W "${type_list}" -- ${cur_word}) ) - - # if no match was found, fall back to filename completion - if [ ${#COMPREPLY[@]} -eq 0 ]; then - COMPREPLY=( $(compgen -f -- "${cur_word}" ) ) - fi - - return 0 -} -complete -F _yargs_completions {{app_name}} -###-end-{{app_name}}-completions-### diff --git a/node_modules/webpack/node_modules/yargs/index.js b/node_modules/webpack/node_modules/yargs/index.js deleted file mode 100644 index 37450cf7a..000000000 --- a/node_modules/webpack/node_modules/yargs/index.js +++ /dev/null @@ -1,31 +0,0 @@ -// classic singleton yargs API, to use yargs -// without running as a singleton do: -// require('yargs/yargs')(process.argv.slice(2)) -const yargs = require('./yargs') - -Argv(process.argv.slice(2)) - -module.exports = Argv - -function Argv (processArgs, cwd) { - const argv = yargs(processArgs, cwd, require) - singletonify(argv) - return argv -} - -/* Hack an instance of Argv with process.argv into Argv - so people can do - require('yargs')(['--beeble=1','-z','zizzle']).argv - to parse a list of args and - require('yargs').argv - to get a parsed version of process.argv. -*/ -function singletonify (inst) { - Object.keys(inst).forEach(function (key) { - if (key === 'argv') { - Argv.__defineGetter__(key, inst.__lookupGetter__(key)) - } else { - Argv[key] = typeof inst[key] === 'function' ? inst[key].bind(inst) : inst[key] - } - }) -} diff --git a/node_modules/webpack/node_modules/yargs/lib/apply-extends.js b/node_modules/webpack/node_modules/yargs/lib/apply-extends.js deleted file mode 100644 index 5fc69fab1..000000000 --- a/node_modules/webpack/node_modules/yargs/lib/apply-extends.js +++ /dev/null @@ -1,52 +0,0 @@ -var fs = require('fs') -var path = require('path') -var assign = require('./assign') -var YError = require('./yerror') - -var previouslyVisitedConfigs = [] - -function checkForCircularExtends (path) { - if (previouslyVisitedConfigs.indexOf(path) > -1) { - throw new YError("Circular extended configurations: '" + path + "'.") - } -} - -function getPathToDefaultConfig (cwd, pathToExtend) { - return path.resolve(cwd, pathToExtend) -} - -function applyExtends (config, cwd) { - var defaultConfig = {} - - if (config.hasOwnProperty('extends')) { - if (typeof config.extends !== 'string') return defaultConfig - var isPath = /\.json$/.test(config.extends) - var pathToDefault = null - if (!isPath) { - try { - pathToDefault = require.resolve(config.extends) - } catch (err) { - // most likely this simply isn't a module. - } - } else { - pathToDefault = getPathToDefaultConfig(cwd, config.extends) - } - // maybe the module uses key for some other reason, - // err on side of caution. - if (!pathToDefault && !isPath) return config - - checkForCircularExtends(pathToDefault) - - previouslyVisitedConfigs.push(pathToDefault) - - defaultConfig = isPath ? JSON.parse(fs.readFileSync(pathToDefault, 'utf8')) : require(config.extends) - delete config.extends - defaultConfig = applyExtends(defaultConfig, path.dirname(pathToDefault)) - } - - previouslyVisitedConfigs = [] - - return assign(defaultConfig, config) -} - -module.exports = applyExtends diff --git a/node_modules/webpack/node_modules/yargs/lib/argsert.js b/node_modules/webpack/node_modules/yargs/lib/argsert.js deleted file mode 100644 index d3e72fce5..000000000 --- a/node_modules/webpack/node_modules/yargs/lib/argsert.js +++ /dev/null @@ -1,72 +0,0 @@ -const command = require('./command')() -const YError = require('./yerror') - -const positionName = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth'] - -module.exports = function (expected, callerArguments, length) { - // TODO: should this eventually raise an exception. - try { - // preface the argument description with "cmd", so - // that we can run it through yargs' command parser. - var position = 0 - var parsed = {demanded: [], optional: []} - if (typeof expected === 'object') { - length = callerArguments - callerArguments = expected - } else { - parsed = command.parseCommand('cmd ' + expected) - } - const args = [].slice.call(callerArguments) - - while (args.length && args[args.length - 1] === undefined) args.pop() - length = length || args.length - - if (length < parsed.demanded.length) { - throw new YError('Not enough arguments provided. Expected ' + parsed.demanded.length + - ' but received ' + args.length + '.') - } - - const totalCommands = parsed.demanded.length + parsed.optional.length - if (length > totalCommands) { - throw new YError('Too many arguments provided. Expected max ' + totalCommands + - ' but received ' + length + '.') - } - - parsed.demanded.forEach(function (demanded) { - const arg = args.shift() - const observedType = guessType(arg) - const matchingTypes = demanded.cmd.filter(function (type) { - return type === observedType || type === '*' - }) - if (matchingTypes.length === 0) argumentTypeError(observedType, demanded.cmd, position, false) - position += 1 - }) - - parsed.optional.forEach(function (optional) { - if (args.length === 0) return - const arg = args.shift() - const observedType = guessType(arg) - const matchingTypes = optional.cmd.filter(function (type) { - return type === observedType || type === '*' - }) - if (matchingTypes.length === 0) argumentTypeError(observedType, optional.cmd, position, true) - position += 1 - }) - } catch (err) { - console.warn(err.stack) - } -} - -function guessType (arg) { - if (Array.isArray(arg)) { - return 'array' - } else if (arg === null) { - return 'null' - } - return typeof arg -} - -function argumentTypeError (observedType, allowedTypes, position, optional) { - throw new YError('Invalid ' + (positionName[position] || 'manyith') + ' argument.' + - ' Expected ' + allowedTypes.join(' or ') + ' but received ' + observedType + '.') -} diff --git a/node_modules/webpack/node_modules/yargs/lib/assign.js b/node_modules/webpack/node_modules/yargs/lib/assign.js deleted file mode 100644 index 7d5a3cef2..000000000 --- a/node_modules/webpack/node_modules/yargs/lib/assign.js +++ /dev/null @@ -1,15 +0,0 @@ -// lazy Object.assign logic that only works for merging -// two objects; eventually we should replace this with Object.assign. -module.exports = function assign (defaults, configuration) { - var o = {} - configuration = configuration || {} - - Object.keys(defaults).forEach(function (k) { - o[k] = defaults[k] - }) - Object.keys(configuration).forEach(function (k) { - o[k] = configuration[k] - }) - - return o -} diff --git a/node_modules/webpack/node_modules/yargs/lib/command.js b/node_modules/webpack/node_modules/yargs/lib/command.js deleted file mode 100644 index 3567cf953..000000000 --- a/node_modules/webpack/node_modules/yargs/lib/command.js +++ /dev/null @@ -1,336 +0,0 @@ -const path = require('path') -const inspect = require('util').inspect -const camelCase = require('camelcase') - -const DEFAULT_MARKER = '*' - -// handles parsing positional arguments, -// and populating argv with said positional -// arguments. -module.exports = function (yargs, usage, validation) { - const self = {} - - var handlers = {} - var aliasMap = {} - var defaultCommand - self.addHandler = function (cmd, description, builder, handler) { - var aliases = [] - handler = handler || function () {} - - if (Array.isArray(cmd)) { - aliases = cmd.slice(1) - cmd = cmd[0] - } else if (typeof cmd === 'object') { - var command = (Array.isArray(cmd.command) || typeof cmd.command === 'string') ? cmd.command : moduleName(cmd) - if (cmd.aliases) command = [].concat(command).concat(cmd.aliases) - self.addHandler(command, extractDesc(cmd), cmd.builder, cmd.handler) - return - } - - // allow a module to be provided instead of separate builder and handler - if (typeof builder === 'object' && builder.builder && typeof builder.handler === 'function') { - self.addHandler([cmd].concat(aliases), description, builder.builder, builder.handler) - return - } - - // parse positionals out of cmd string - var parsedCommand = self.parseCommand(cmd) - - // remove positional args from aliases only - aliases = aliases.map(function (alias) { - return self.parseCommand(alias).cmd - }) - - // check for default and filter out '*'' - var isDefault = false - var parsedAliases = [parsedCommand.cmd].concat(aliases).filter(function (c) { - if (c === DEFAULT_MARKER) { - isDefault = true - return false - } - return true - }) - - // short-circuit if default with no aliases - if (isDefault && parsedAliases.length === 0) { - defaultCommand = { - original: cmd.replace(DEFAULT_MARKER, '').trim(), - handler: handler, - builder: builder || {}, - demanded: parsedCommand.demanded, - optional: parsedCommand.optional - } - return - } - - // shift cmd and aliases after filtering out '*' - if (isDefault) { - parsedCommand.cmd = parsedAliases[0] - aliases = parsedAliases.slice(1) - cmd = cmd.replace(DEFAULT_MARKER, parsedCommand.cmd) - } - - // populate aliasMap - aliases.forEach(function (alias) { - aliasMap[alias] = parsedCommand.cmd - }) - - if (description !== false) { - usage.command(cmd, description, isDefault, aliases) - } - - handlers[parsedCommand.cmd] = { - original: cmd, - handler: handler, - builder: builder || {}, - demanded: parsedCommand.demanded, - optional: parsedCommand.optional - } - - if (isDefault) defaultCommand = handlers[parsedCommand.cmd] - } - - self.addDirectory = function (dir, context, req, callerFile, opts) { - opts = opts || {} - // disable recursion to support nested directories of subcommands - if (typeof opts.recurse !== 'boolean') opts.recurse = false - // exclude 'json', 'coffee' from require-directory defaults - if (!Array.isArray(opts.extensions)) opts.extensions = ['js'] - // allow consumer to define their own visitor function - const parentVisit = typeof opts.visit === 'function' ? opts.visit : function (o) { return o } - // call addHandler via visitor function - opts.visit = function (obj, joined, filename) { - const visited = parentVisit(obj, joined, filename) - // allow consumer to skip modules with their own visitor - if (visited) { - // check for cyclic reference - // each command file path should only be seen once per execution - if (~context.files.indexOf(joined)) return visited - // keep track of visited files in context.files - context.files.push(joined) - self.addHandler(visited) - } - return visited - } - require('require-directory')({ require: req, filename: callerFile }, dir, opts) - } - - // lookup module object from require()d command and derive name - // if module was not require()d and no name given, throw error - function moduleName (obj) { - const mod = require('which-module')(obj) - if (!mod) throw new Error('No command name given for module: ' + inspect(obj)) - return commandFromFilename(mod.filename) - } - - // derive command name from filename - function commandFromFilename (filename) { - return path.basename(filename, path.extname(filename)) - } - - function extractDesc (obj) { - for (var keys = ['describe', 'description', 'desc'], i = 0, l = keys.length, test; i < l; i++) { - test = obj[keys[i]] - if (typeof test === 'string' || typeof test === 'boolean') return test - } - return false - } - - self.parseCommand = function (cmd) { - var extraSpacesStrippedCommand = cmd.replace(/\s{2,}/g, ' ') - var splitCommand = extraSpacesStrippedCommand.split(/\s+(?![^[]*]|[^<]*>)/) - var bregex = /\.*[\][<>]/g - var parsedCommand = { - cmd: (splitCommand.shift()).replace(bregex, ''), - demanded: [], - optional: [] - } - splitCommand.forEach(function (cmd, i) { - var variadic = false - cmd = cmd.replace(/\s/g, '') - if (/\.+[\]>]/.test(cmd) && i === splitCommand.length - 1) variadic = true - if (/^\[/.test(cmd)) { - parsedCommand.optional.push({ - cmd: cmd.replace(bregex, '').split('|'), - variadic: variadic - }) - } else { - parsedCommand.demanded.push({ - cmd: cmd.replace(bregex, '').split('|'), - variadic: variadic - }) - } - }) - return parsedCommand - } - - self.getCommands = function () { - return Object.keys(handlers).concat(Object.keys(aliasMap)) - } - - self.getCommandHandlers = function () { - return handlers - } - - self.hasDefaultCommand = function () { - return !!defaultCommand - } - - self.runCommand = function (command, yargs, parsed, commandIndex) { - var aliases = parsed.aliases - var commandHandler = handlers[command] || handlers[aliasMap[command]] || defaultCommand - var currentContext = yargs.getContext() - var numFiles = currentContext.files.length - var parentCommands = currentContext.commands.slice() - - // what does yargs look like after the buidler is run? - var innerArgv = parsed.argv - var innerYargs = null - var positionalMap = {} - - if (command) currentContext.commands.push(command) - if (typeof commandHandler.builder === 'function') { - // a function can be provided, which builds - // up a yargs chain and possibly returns it. - innerYargs = commandHandler.builder(yargs.reset(parsed.aliases)) - // if the builder function did not yet parse argv with reset yargs - // and did not explicitly set a usage() string, then apply the - // original command string as usage() for consistent behavior with - // options object below. - if (yargs.parsed === false) { - if (typeof yargs.getUsageInstance().getUsage() === 'undefined') { - yargs.usage('$0 ' + (parentCommands.length ? parentCommands.join(' ') + ' ' : '') + commandHandler.original) - } - innerArgv = innerYargs ? innerYargs._parseArgs(null, null, true, commandIndex) : yargs._parseArgs(null, null, true, commandIndex) - } else { - innerArgv = yargs.parsed.argv - } - - if (innerYargs && yargs.parsed === false) aliases = innerYargs.parsed.aliases - else aliases = yargs.parsed.aliases - } else if (typeof commandHandler.builder === 'object') { - // as a short hand, an object can instead be provided, specifying - // the options that a command takes. - innerYargs = yargs.reset(parsed.aliases) - innerYargs.usage('$0 ' + (parentCommands.length ? parentCommands.join(' ') + ' ' : '') + commandHandler.original) - Object.keys(commandHandler.builder).forEach(function (key) { - innerYargs.option(key, commandHandler.builder[key]) - }) - innerArgv = innerYargs._parseArgs(null, null, true, commandIndex) - aliases = innerYargs.parsed.aliases - } - - if (!yargs._hasOutput()) { - positionalMap = populatePositionals(commandHandler, innerArgv, currentContext, yargs) - } - - // we apply validation post-hoc, so that custom - // checks get passed populated positional arguments. - if (!yargs._hasOutput()) yargs._runValidation(innerArgv, aliases, positionalMap, yargs.parsed.error) - - if (commandHandler.handler && !yargs._hasOutput()) { - yargs._setHasOutput() - commandHandler.handler(innerArgv) - } - - if (command) currentContext.commands.pop() - numFiles = currentContext.files.length - numFiles - if (numFiles > 0) currentContext.files.splice(numFiles * -1, numFiles) - - return innerArgv - } - - // transcribe all positional arguments "command <foo> <bar> [apple]" - // onto argv. - function populatePositionals (commandHandler, argv, context, yargs) { - argv._ = argv._.slice(context.commands.length) // nuke the current commands - var demanded = commandHandler.demanded.slice(0) - var optional = commandHandler.optional.slice(0) - var positionalMap = {} - - validation.positionalCount(demanded.length, argv._.length) - - while (demanded.length) { - var demand = demanded.shift() - populatePositional(demand, argv, yargs, positionalMap) - } - - while (optional.length) { - var maybe = optional.shift() - populatePositional(maybe, argv, yargs, positionalMap) - } - - argv._ = context.commands.concat(argv._) - return positionalMap - } - - // populate a single positional argument and its - // aliases onto argv. - function populatePositional (positional, argv, yargs, positionalMap) { - // "positional" consists of the positional.cmd, an array representing - // the positional's name and aliases, and positional.variadic - // indicating whether or not it is a variadic array. - var variadics = null - var value = null - for (var i = 0, cmd; (cmd = positional.cmd[i]) !== undefined; i++) { - if (positional.variadic) { - if (variadics) argv[cmd] = variadics.slice(0) - else argv[cmd] = variadics = argv._.splice(0) - } else { - if (!value && !argv._.length) continue - if (value) argv[cmd] = value - else argv[cmd] = value = argv._.shift() - } - positionalMap[cmd] = true - postProcessPositional(yargs, argv, cmd) - addCamelCaseExpansions(argv, cmd) - } - } - - // TODO move positional arg logic to yargs-parser and remove this duplication - function postProcessPositional (yargs, argv, key) { - var coerce = yargs.getOptions().coerce[key] - if (typeof coerce === 'function') { - try { - argv[key] = coerce(argv[key]) - } catch (err) { - yargs.getUsageInstance().fail(err.message, err) - } - } - } - - function addCamelCaseExpansions (argv, option) { - if (/-/.test(option)) { - const cc = camelCase(option) - if (typeof argv[option] === 'object') argv[cc] = argv[option].slice(0) - else argv[cc] = argv[option] - } - } - - self.reset = function () { - handlers = {} - aliasMap = {} - defaultCommand = undefined - return self - } - - // used by yargs.parse() to freeze - // the state of commands such that - // we can apply .parse() multiple times - // with the same yargs instance. - var frozen - self.freeze = function () { - frozen = {} - frozen.handlers = handlers - frozen.aliasMap = aliasMap - frozen.defaultCommand = defaultCommand - } - self.unfreeze = function () { - handlers = frozen.handlers - aliasMap = frozen.aliasMap - defaultCommand = frozen.defaultCommand - frozen = undefined - } - - return self -} diff --git a/node_modules/webpack/node_modules/yargs/lib/completion.js b/node_modules/webpack/node_modules/yargs/lib/completion.js deleted file mode 100644 index 5cd9a18a0..000000000 --- a/node_modules/webpack/node_modules/yargs/lib/completion.js +++ /dev/null @@ -1,104 +0,0 @@ -const fs = require('fs') -const path = require('path') - -// add bash completions to your -// yargs-powered applications. -module.exports = function (yargs, usage, command) { - const self = { - completionKey: 'get-yargs-completions' - } - - // get a list of completion commands. - // 'args' is the array of strings from the line to be completed - self.getCompletion = function (args, done) { - const completions = [] - const current = args.length ? args[args.length - 1] : '' - const argv = yargs.parse(args, true) - const aliases = yargs.parsed.aliases - - // a custom completion function can be provided - // to completion(). - if (completionFunction) { - if (completionFunction.length < 3) { - var result = completionFunction(current, argv) - - // promise based completion function. - if (typeof result.then === 'function') { - return result.then(function (list) { - process.nextTick(function () { done(list) }) - }).catch(function (err) { - process.nextTick(function () { throw err }) - }) - } - - // synchronous completion function. - return done(result) - } else { - // asynchronous completion function - return completionFunction(current, argv, function (completions) { - done(completions) - }) - } - } - - var handlers = command.getCommandHandlers() - for (var i = 0, ii = args.length; i < ii; ++i) { - if (handlers[args[i]] && handlers[args[i]].builder) { - const builder = handlers[args[i]].builder - if (typeof builder === 'function') { - const y = yargs.reset() - builder(y) - return y.argv - } - } - } - - if (!current.match(/^-/)) { - usage.getCommands().forEach(function (command) { - if (args.indexOf(command[0]) === -1) { - completions.push(command[0]) - } - }) - } - - if (current.match(/^-/)) { - Object.keys(yargs.getOptions().key).forEach(function (key) { - // If the key and its aliases aren't in 'args', add the key to 'completions' - var keyAndAliases = [key].concat(aliases[key] || []) - var notInArgs = keyAndAliases.every(function (val) { - return args.indexOf('--' + val) === -1 - }) - if (notInArgs) { - completions.push('--' + key) - } - }) - } - - done(completions) - } - - // generate the completion script to add to your .bashrc. - self.generateCompletionScript = function ($0) { - var script = fs.readFileSync( - path.resolve(__dirname, '../completion.sh.hbs'), - 'utf-8' - ) - var name = path.basename($0) - - // add ./to applications not yet installed as bin. - if ($0.match(/\.js$/)) $0 = './' + $0 - - script = script.replace(/{{app_name}}/g, name) - return script.replace(/{{app_path}}/g, $0) - } - - // register a function to perform your own custom - // completions., this function can be either - // synchrnous or asynchronous. - var completionFunction = null - self.registerFunction = function (fn) { - completionFunction = fn - } - - return self -} diff --git a/node_modules/webpack/node_modules/yargs/lib/levenshtein.js b/node_modules/webpack/node_modules/yargs/lib/levenshtein.js deleted file mode 100644 index 6ec216f59..000000000 --- a/node_modules/webpack/node_modules/yargs/lib/levenshtein.js +++ /dev/null @@ -1,47 +0,0 @@ -/* -Copyright (c) 2011 Andrei Mackenzie - -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. -*/ - -// levenshtein distance algorithm, pulled from Andrei Mackenzie's MIT licensed. -// gist, which can be found here: https://gist.github.com/andrei-m/982927 - -// Compute the edit distance between the two given strings -module.exports = function (a, b) { - if (a.length === 0) return b.length - if (b.length === 0) return a.length - - var matrix = [] - - // increment along the first column of each row - var i - for (i = 0; i <= b.length; i++) { - matrix[i] = [i] - } - - // increment each column in the first row - var j - for (j = 0; j <= a.length; j++) { - matrix[0][j] = j - } - - // Fill in the rest of the matrix - for (i = 1; i <= b.length; i++) { - for (j = 1; j <= a.length; j++) { - if (b.charAt(i - 1) === a.charAt(j - 1)) { - matrix[i][j] = matrix[i - 1][j - 1] - } else { - matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, // substitution - Math.min(matrix[i][j - 1] + 1, // insertion - matrix[i - 1][j] + 1)) // deletion - } - } - } - - return matrix[b.length][a.length] -} diff --git a/node_modules/webpack/node_modules/yargs/lib/obj-filter.js b/node_modules/webpack/node_modules/yargs/lib/obj-filter.js deleted file mode 100644 index 42cb9961e..000000000 --- a/node_modules/webpack/node_modules/yargs/lib/obj-filter.js +++ /dev/null @@ -1,10 +0,0 @@ -module.exports = function (original, filter) { - const obj = {} - filter = filter || function (k, v) { return true } - Object.keys(original || {}).forEach(function (key) { - if (filter(key, original[key])) { - obj[key] = original[key] - } - }) - return obj -} diff --git a/node_modules/webpack/node_modules/yargs/lib/usage.js b/node_modules/webpack/node_modules/yargs/lib/usage.js deleted file mode 100644 index 43f71225c..000000000 --- a/node_modules/webpack/node_modules/yargs/lib/usage.js +++ /dev/null @@ -1,489 +0,0 @@ -// this file handles outputting usage instructions, -// failures, etc. keeps logging in one place. -const stringWidth = require('string-width') -const objFilter = require('./obj-filter') -const setBlocking = require('set-blocking') -const YError = require('./yerror') - -module.exports = function (yargs, y18n) { - const __ = y18n.__ - const self = {} - - // methods for ouputting/building failure message. - var fails = [] - self.failFn = function (f) { - fails.push(f) - } - - var failMessage = null - var showHelpOnFail = true - self.showHelpOnFail = function (enabled, message) { - if (typeof enabled === 'string') { - message = enabled - enabled = true - } else if (typeof enabled === 'undefined') { - enabled = true - } - failMessage = message - showHelpOnFail = enabled - return self - } - - var failureOutput = false - self.fail = function (msg, err) { - const logger = yargs._getLoggerInstance() - - if (fails.length) { - for (var i = fails.length - 1; i >= 0; --i) { - fails[i](msg, err, self) - } - } else { - if (yargs.getExitProcess()) setBlocking(true) - - // don't output failure message more than once - if (!failureOutput) { - failureOutput = true - if (showHelpOnFail) yargs.showHelp('error') - if (msg) logger.error(msg) - if (failMessage) { - if (msg) logger.error('') - logger.error(failMessage) - } - } - - err = err || new YError(msg) - if (yargs.getExitProcess()) { - return yargs.exit(1) - } else if (yargs._hasParseCallback()) { - return yargs.exit(1, err) - } else { - throw err - } - } - } - - // methods for ouputting/building help (usage) message. - var usage - self.usage = function (msg) { - usage = msg - } - self.getUsage = function () { - return usage - } - - var examples = [] - self.example = function (cmd, description) { - examples.push([cmd, description || '']) - } - - var commands = [] - self.command = function (cmd, description, isDefault, aliases) { - // the last default wins, so cancel out any previously set default - if (isDefault) { - commands = commands.map(function (cmdArray) { - cmdArray[2] = false - return cmdArray - }) - } - commands.push([cmd, description || '', isDefault, aliases]) - } - self.getCommands = function () { - return commands - } - - var descriptions = {} - self.describe = function (key, desc) { - if (typeof key === 'object') { - Object.keys(key).forEach(function (k) { - self.describe(k, key[k]) - }) - } else { - descriptions[key] = desc - } - } - self.getDescriptions = function () { - return descriptions - } - - var epilog - self.epilog = function (msg) { - epilog = msg - } - - var wrapSet = false - var wrap - self.wrap = function (cols) { - wrapSet = true - wrap = cols - } - - function getWrap () { - if (!wrapSet) { - wrap = windowWidth() - wrapSet = true - } - - return wrap - } - - var deferY18nLookupPrefix = '__yargsString__:' - self.deferY18nLookup = function (str) { - return deferY18nLookupPrefix + str - } - - var defaultGroup = 'Options:' - self.help = function () { - normalizeAliases() - - // handle old demanded API - var demandedOptions = yargs.getDemandedOptions() - var demandedCommands = yargs.getDemandedCommands() - var groups = yargs.getGroups() - var options = yargs.getOptions() - var keys = Object.keys( - Object.keys(descriptions) - .concat(Object.keys(demandedOptions)) - .concat(Object.keys(demandedCommands)) - .concat(Object.keys(options.default)) - .reduce(function (acc, key) { - if (key !== '_') acc[key] = true - return acc - }, {}) - ) - - var theWrap = getWrap() - var ui = require('cliui')({ - width: theWrap, - wrap: !!theWrap - }) - - // the usage string. - if (usage) { - var u = usage.replace(/\$0/g, yargs.$0) - ui.div(u + '\n') - } - - // your application's commands, i.e., non-option - // arguments populated in '_'. - if (commands.length) { - ui.div(__('Commands:')) - - commands.forEach(function (command) { - ui.span( - {text: command[0], padding: [0, 2, 0, 2], width: maxWidth(commands, theWrap) + 4}, - {text: command[1]} - ) - var hints = [] - if (command[2]) hints.push('[' + __('default:').slice(0, -1) + ']') // TODO hacking around i18n here - if (command[3] && command[3].length) { - hints.push('[' + __('aliases:') + ' ' + command[3].join(', ') + ']') - } - if (hints.length) { - ui.div({text: hints.join(' '), padding: [0, 0, 0, 2], align: 'right'}) - } else { - ui.div() - } - }) - - ui.div() - } - - // perform some cleanup on the keys array, making it - // only include top-level keys not their aliases. - var aliasKeys = (Object.keys(options.alias) || []) - .concat(Object.keys(yargs.parsed.newAliases) || []) - - keys = keys.filter(function (key) { - return !yargs.parsed.newAliases[key] && aliasKeys.every(function (alias) { - return (options.alias[alias] || []).indexOf(key) === -1 - }) - }) - - // populate 'Options:' group with any keys that have not - // explicitly had a group set. - if (!groups[defaultGroup]) groups[defaultGroup] = [] - addUngroupedKeys(keys, options.alias, groups) - - // display 'Options:' table along with any custom tables: - Object.keys(groups).forEach(function (groupName) { - if (!groups[groupName].length) return - - ui.div(__(groupName)) - - // if we've grouped the key 'f', but 'f' aliases 'foobar', - // normalizedKeys should contain only 'foobar'. - var normalizedKeys = groups[groupName].map(function (key) { - if (~aliasKeys.indexOf(key)) return key - for (var i = 0, aliasKey; (aliasKey = aliasKeys[i]) !== undefined; i++) { - if (~(options.alias[aliasKey] || []).indexOf(key)) return aliasKey - } - return key - }) - - // actually generate the switches string --foo, -f, --bar. - var switches = normalizedKeys.reduce(function (acc, key) { - acc[key] = [ key ].concat(options.alias[key] || []) - .map(function (sw) { - return (sw.length > 1 ? '--' : '-') + sw - }) - .join(', ') - - return acc - }, {}) - - normalizedKeys.forEach(function (key) { - var kswitch = switches[key] - var desc = descriptions[key] || '' - var type = null - - if (~desc.lastIndexOf(deferY18nLookupPrefix)) desc = __(desc.substring(deferY18nLookupPrefix.length)) - - if (~options.boolean.indexOf(key)) type = '[' + __('boolean') + ']' - if (~options.count.indexOf(key)) type = '[' + __('count') + ']' - if (~options.string.indexOf(key)) type = '[' + __('string') + ']' - if (~options.normalize.indexOf(key)) type = '[' + __('string') + ']' - if (~options.array.indexOf(key)) type = '[' + __('array') + ']' - if (~options.number.indexOf(key)) type = '[' + __('number') + ']' - - var extra = [ - type, - (key in demandedOptions) ? '[' + __('required') + ']' : null, - options.choices && options.choices[key] ? '[' + __('choices:') + ' ' + - self.stringifiedValues(options.choices[key]) + ']' : null, - defaultString(options.default[key], options.defaultDescription[key]) - ].filter(Boolean).join(' ') - - ui.span( - {text: kswitch, padding: [0, 2, 0, 2], width: maxWidth(switches, theWrap) + 4}, - desc - ) - - if (extra) ui.div({text: extra, padding: [0, 0, 0, 2], align: 'right'}) - else ui.div() - }) - - ui.div() - }) - - // describe some common use-cases for your application. - if (examples.length) { - ui.div(__('Examples:')) - - examples.forEach(function (example) { - example[0] = example[0].replace(/\$0/g, yargs.$0) - }) - - examples.forEach(function (example) { - if (example[1] === '') { - ui.div( - { - text: example[0], - padding: [0, 2, 0, 2] - } - ) - } else { - ui.div( - { - text: example[0], - padding: [0, 2, 0, 2], - width: maxWidth(examples, theWrap) + 4 - }, { - text: example[1] - } - ) - } - }) - - ui.div() - } - - // the usage string. - if (epilog) { - var e = epilog.replace(/\$0/g, yargs.$0) - ui.div(e + '\n') - } - - return ui.toString() - } - - // return the maximum width of a string - // in the left-hand column of a table. - function maxWidth (table, theWrap) { - var width = 0 - - // table might be of the form [leftColumn], - // or {key: leftColumn} - if (!Array.isArray(table)) { - table = Object.keys(table).map(function (key) { - return [table[key]] - }) - } - - table.forEach(function (v) { - width = Math.max(stringWidth(v[0]), width) - }) - - // if we've enabled 'wrap' we should limit - // the max-width of the left-column. - if (theWrap) width = Math.min(width, parseInt(theWrap * 0.5, 10)) - - return width - } - - // make sure any options set for aliases, - // are copied to the keys being aliased. - function normalizeAliases () { - // handle old demanded API - var demandedOptions = yargs.getDemandedOptions() - var options = yargs.getOptions() - - ;(Object.keys(options.alias) || []).forEach(function (key) { - options.alias[key].forEach(function (alias) { - // copy descriptions. - if (descriptions[alias]) self.describe(key, descriptions[alias]) - // copy demanded. - if (alias in demandedOptions) yargs.demandOption(key, demandedOptions[alias]) - // type messages. - if (~options.boolean.indexOf(alias)) yargs.boolean(key) - if (~options.count.indexOf(alias)) yargs.count(key) - if (~options.string.indexOf(alias)) yargs.string(key) - if (~options.normalize.indexOf(alias)) yargs.normalize(key) - if (~options.array.indexOf(alias)) yargs.array(key) - if (~options.number.indexOf(alias)) yargs.number(key) - }) - }) - } - - // given a set of keys, place any keys that are - // ungrouped under the 'Options:' grouping. - function addUngroupedKeys (keys, aliases, groups) { - var groupedKeys = [] - var toCheck = null - Object.keys(groups).forEach(function (group) { - groupedKeys = groupedKeys.concat(groups[group]) - }) - - keys.forEach(function (key) { - toCheck = [key].concat(aliases[key]) - if (!toCheck.some(function (k) { - return groupedKeys.indexOf(k) !== -1 - })) { - groups[defaultGroup].push(key) - } - }) - return groupedKeys - } - - self.showHelp = function (level) { - const logger = yargs._getLoggerInstance() - if (!level) level = 'error' - var emit = typeof level === 'function' ? level : logger[level] - emit(self.help()) - } - - self.functionDescription = function (fn) { - var description = fn.name ? require('decamelize')(fn.name, '-') : __('generated-value') - return ['(', description, ')'].join('') - } - - self.stringifiedValues = function (values, separator) { - var string = '' - var sep = separator || ', ' - var array = [].concat(values) - - if (!values || !array.length) return string - - array.forEach(function (value) { - if (string.length) string += sep - string += JSON.stringify(value) - }) - - return string - } - - // format the default-value-string displayed in - // the right-hand column. - function defaultString (value, defaultDescription) { - var string = '[' + __('default:') + ' ' - - if (value === undefined && !defaultDescription) return null - - if (defaultDescription) { - string += defaultDescription - } else { - switch (typeof value) { - case 'string': - string += JSON.stringify(value) - break - case 'object': - string += JSON.stringify(value) - break - default: - string += value - } - } - - return string + ']' - } - - // guess the width of the console window, max-width 80. - function windowWidth () { - var maxWidth = 80 - if (typeof process === 'object' && process.stdout && process.stdout.columns) { - return Math.min(maxWidth, process.stdout.columns) - } else { - return maxWidth - } - } - - // logic for displaying application version. - var version = null - self.version = function (ver) { - version = ver - } - - self.showVersion = function () { - const logger = yargs._getLoggerInstance() - if (typeof version === 'function') logger.log(version()) - else logger.log(version) - } - - self.reset = function (localLookup) { - // do not reset wrap here - // do not reset fails here - failMessage = null - failureOutput = false - usage = undefined - epilog = undefined - examples = [] - commands = [] - descriptions = objFilter(descriptions, function (k, v) { - return !localLookup[k] - }) - return self - } - - var frozen - self.freeze = function () { - frozen = {} - frozen.failMessage = failMessage - frozen.failureOutput = failureOutput - frozen.usage = usage - frozen.epilog = epilog - frozen.examples = examples - frozen.commands = commands - frozen.descriptions = descriptions - } - self.unfreeze = function () { - failMessage = frozen.failMessage - failureOutput = frozen.failureOutput - usage = frozen.usage - epilog = frozen.epilog - examples = frozen.examples - commands = frozen.commands - descriptions = frozen.descriptions - frozen = undefined - } - - return self -} diff --git a/node_modules/webpack/node_modules/yargs/lib/validation.js b/node_modules/webpack/node_modules/yargs/lib/validation.js deleted file mode 100644 index 2f9ff8e6c..000000000 --- a/node_modules/webpack/node_modules/yargs/lib/validation.js +++ /dev/null @@ -1,364 +0,0 @@ -const objFilter = require('./obj-filter') -const specialKeys = ['$0', '--', '_'] - -// validation-type-stuff, missing params, -// bad implications, custom checks. -module.exports = function (yargs, usage, y18n) { - const __ = y18n.__ - const __n = y18n.__n - const self = {} - - // validate appropriate # of non-option - // arguments were provided, i.e., '_'. - self.nonOptionCount = function (argv) { - const demandedCommands = yargs.getDemandedCommands() - // don't count currently executing commands - const _s = argv._.length - yargs.getContext().commands.length - - if (demandedCommands._ && (_s < demandedCommands._.min || _s > demandedCommands._.max)) { - if (_s < demandedCommands._.min) { - if (demandedCommands._.minMsg !== undefined) { - usage.fail( - // replace $0 with observed, $1 with expected. - demandedCommands._.minMsg ? demandedCommands._.minMsg.replace(/\$0/g, _s).replace(/\$1/, demandedCommands._.min) : null - ) - } else { - usage.fail( - __('Not enough non-option arguments: got %s, need at least %s', _s, demandedCommands._.min) - ) - } - } else if (_s > demandedCommands._.max) { - if (demandedCommands._.maxMsg !== undefined) { - usage.fail( - // replace $0 with observed, $1 with expected. - demandedCommands._.maxMsg ? demandedCommands._.maxMsg.replace(/\$0/g, _s).replace(/\$1/, demandedCommands._.max) : null - ) - } else { - usage.fail( - __('Too many non-option arguments: got %s, maximum of %s', _s, demandedCommands._.max) - ) - } - } - } - } - - // validate the appropriate # of <required> - // positional arguments were provided: - self.positionalCount = function (required, observed) { - if (observed < required) { - usage.fail( - __('Not enough non-option arguments: got %s, need at least %s', observed, required) - ) - } - } - - // make sure that any args that require an - // value (--foo=bar), have a value. - self.missingArgumentValue = function (argv) { - const defaultValues = [true, false, ''] - const options = yargs.getOptions() - - if (options.requiresArg.length > 0) { - const missingRequiredArgs = [] - - options.requiresArg.forEach(function (key) { - const value = argv[key] - - // if a value is explicitly requested, - // flag argument as missing if it does not - // look like foo=bar was entered. - if (~defaultValues.indexOf(value) || - (Array.isArray(value) && !value.length)) { - missingRequiredArgs.push(key) - } - }) - - if (missingRequiredArgs.length > 0) { - usage.fail(__n( - 'Missing argument value: %s', - 'Missing argument values: %s', - missingRequiredArgs.length, - missingRequiredArgs.join(', ') - )) - } - } - } - - // make sure all the required arguments are present. - self.requiredArguments = function (argv) { - const demandedOptions = yargs.getDemandedOptions() - var missing = null - - Object.keys(demandedOptions).forEach(function (key) { - if (!argv.hasOwnProperty(key) || typeof argv[key] === 'undefined') { - missing = missing || {} - missing[key] = demandedOptions[key] - } - }) - - if (missing) { - const customMsgs = [] - Object.keys(missing).forEach(function (key) { - const msg = missing[key] - if (msg && customMsgs.indexOf(msg) < 0) { - customMsgs.push(msg) - } - }) - - const customMsg = customMsgs.length ? '\n' + customMsgs.join('\n') : '' - - usage.fail(__n( - 'Missing required argument: %s', - 'Missing required arguments: %s', - Object.keys(missing).length, - Object.keys(missing).join(', ') + customMsg - )) - } - } - - // check for unknown arguments (strict-mode). - self.unknownArguments = function (argv, aliases, positionalMap) { - const aliasLookup = {} - const descriptions = usage.getDescriptions() - const demandedOptions = yargs.getDemandedOptions() - const commandKeys = yargs.getCommandInstance().getCommands() - const unknown = [] - const currentContext = yargs.getContext() - - Object.keys(aliases).forEach(function (key) { - aliases[key].forEach(function (alias) { - aliasLookup[alias] = key - }) - }) - - Object.keys(argv).forEach(function (key) { - if (specialKeys.indexOf(key) === -1 && - !descriptions.hasOwnProperty(key) && - !demandedOptions.hasOwnProperty(key) && - !positionalMap.hasOwnProperty(key) && - !yargs._getParseContext().hasOwnProperty(key) && - !aliasLookup.hasOwnProperty(key)) { - unknown.push(key) - } - }) - - if (commandKeys.length > 0) { - argv._.slice(currentContext.commands.length).forEach(function (key) { - if (commandKeys.indexOf(key) === -1) { - unknown.push(key) - } - }) - } - - if (unknown.length > 0) { - usage.fail(__n( - 'Unknown argument: %s', - 'Unknown arguments: %s', - unknown.length, - unknown.join(', ') - )) - } - } - - // validate arguments limited to enumerated choices - self.limitedChoices = function (argv) { - const options = yargs.getOptions() - const invalid = {} - - if (!Object.keys(options.choices).length) return - - Object.keys(argv).forEach(function (key) { - if (specialKeys.indexOf(key) === -1 && - options.choices.hasOwnProperty(key)) { - [].concat(argv[key]).forEach(function (value) { - // TODO case-insensitive configurability - if (options.choices[key].indexOf(value) === -1) { - invalid[key] = (invalid[key] || []).concat(value) - } - }) - } - }) - - const invalidKeys = Object.keys(invalid) - - if (!invalidKeys.length) return - - var msg = __('Invalid values:') - invalidKeys.forEach(function (key) { - msg += '\n ' + __( - 'Argument: %s, Given: %s, Choices: %s', - key, - usage.stringifiedValues(invalid[key]), - usage.stringifiedValues(options.choices[key]) - ) - }) - usage.fail(msg) - } - - // custom checks, added using the `check` option on yargs. - var checks = [] - self.check = function (f, global) { - checks.push({ - func: f, - global: global - }) - } - - self.customChecks = function (argv, aliases) { - for (var i = 0, f; (f = checks[i]) !== undefined; i++) { - var func = f.func - var result = null - try { - result = func(argv, aliases) - } catch (err) { - usage.fail(err.message ? err.message : err, err) - continue - } - - if (!result) { - usage.fail(__('Argument check failed: %s', func.toString())) - } else if (typeof result === 'string' || result instanceof Error) { - usage.fail(result.toString(), result) - } - } - } - - // check implications, argument foo implies => argument bar. - var implied = {} - self.implies = function (key, value) { - if (typeof key === 'object') { - Object.keys(key).forEach(function (k) { - self.implies(k, key[k]) - }) - } else { - yargs.global(key) - implied[key] = value - } - } - self.getImplied = function () { - return implied - } - - self.implications = function (argv) { - const implyFail = [] - - Object.keys(implied).forEach(function (key) { - var num - const origKey = key - var value = implied[key] - - // convert string '1' to number 1 - num = Number(key) - key = isNaN(num) ? key : num - - if (typeof key === 'number') { - // check length of argv._ - key = argv._.length >= key - } else if (key.match(/^--no-.+/)) { - // check if key doesn't exist - key = key.match(/^--no-(.+)/)[1] - key = !argv[key] - } else { - // check if key exists - key = argv[key] - } - - num = Number(value) - value = isNaN(num) ? value : num - - if (typeof value === 'number') { - value = argv._.length >= value - } else if (value.match(/^--no-.+/)) { - value = value.match(/^--no-(.+)/)[1] - value = !argv[value] - } else { - value = argv[value] - } - - if (key && !value) { - implyFail.push(origKey) - } - }) - - if (implyFail.length) { - var msg = __('Implications failed:') + '\n' - - implyFail.forEach(function (key) { - msg += (' ' + key + ' -> ' + implied[key]) - }) - - usage.fail(msg) - } - } - - var conflicting = {} - self.conflicts = function (key, value) { - if (typeof key === 'object') { - Object.keys(key).forEach(function (k) { - self.conflicts(k, key[k]) - }) - } else { - yargs.global(key) - conflicting[key] = value - } - } - self.getConflicting = function () { - return conflicting - } - - self.conflicting = function (argv) { - var args = Object.getOwnPropertyNames(argv) - - args.forEach(function (arg) { - if (conflicting[arg] && args.indexOf(conflicting[arg]) !== -1) { - usage.fail(__('Arguments %s and %s are mutually exclusive', arg, conflicting[arg])) - } - }) - } - - self.recommendCommands = function (cmd, potentialCommands) { - const distance = require('./levenshtein') - const threshold = 3 // if it takes more than three edits, let's move on. - potentialCommands = potentialCommands.sort(function (a, b) { return b.length - a.length }) - - var recommended = null - var bestDistance = Infinity - for (var i = 0, candidate; (candidate = potentialCommands[i]) !== undefined; i++) { - var d = distance(cmd, candidate) - if (d <= threshold && d < bestDistance) { - bestDistance = d - recommended = candidate - } - } - if (recommended) usage.fail(__('Did you mean %s?', recommended)) - } - - self.reset = function (localLookup) { - implied = objFilter(implied, function (k, v) { - return !localLookup[k] - }) - conflicting = objFilter(conflicting, function (k, v) { - return !localLookup[k] - }) - checks = checks.filter(function (c) { - return c.global - }) - return self - } - - var frozen - self.freeze = function () { - frozen = {} - frozen.implied = implied - frozen.checks = checks - frozen.conflicting = conflicting - } - self.unfreeze = function () { - implied = frozen.implied - checks = frozen.checks - conflicting = frozen.conflicting - frozen = undefined - } - - return self -} diff --git a/node_modules/webpack/node_modules/yargs/lib/yerror.js b/node_modules/webpack/node_modules/yargs/lib/yerror.js deleted file mode 100644 index ad96a8776..000000000 --- a/node_modules/webpack/node_modules/yargs/lib/yerror.js +++ /dev/null @@ -1,10 +0,0 @@ -function YError (msg) { - this.name = 'YError' - this.message = msg || 'yargs error' - Error.captureStackTrace(this, YError) -} - -YError.prototype = Object.create(Error.prototype) -YError.prototype.constructor = YError - -module.exports = YError diff --git a/node_modules/webpack/node_modules/yargs/locales/be.json b/node_modules/webpack/node_modules/yargs/locales/be.json deleted file mode 100644 index 141ebe1e1..000000000 --- a/node_modules/webpack/node_modules/yargs/locales/be.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "Commands:": "Каманды:", - "Options:": "Опцыі:", - "Examples:": "Прыклады:", - "boolean": "булевы тып", - "count": "падлік", - "string": "радковы тып", - "number": "лік", - "array": "масіў", - "required": "неабходна", - "default:": "па змаўчанні:", - "choices:": "магчымасці:", - "aliases:": "аліасы:", - "generated-value": "згенераванае значэнне", - "Not enough non-option arguments: got %s, need at least %s": "Недастаткова неапцыйных аргументаў: ёсць %s, трэба як мінімум %s", - "Too many non-option arguments: got %s, maximum of %s": "Занадта шмат неапцыйных аргументаў: ёсць %s, максімум дапушчальна %s", - "Missing argument value: %s": { - "one": "Не хапае значэння аргументу: %s", - "other": "Не хапае значэнняў аргументаў: %s" - }, - "Missing required argument: %s": { - "one": "Не хапае неабходнага аргументу: %s", - "other": "Не хапае неабходных аргументаў: %s" - }, - "Unknown argument: %s": { - "one": "Невядомы аргумент: %s", - "other": "Невядомыя аргументы: %s" - }, - "Invalid values:": "Несапраўдныя значэння:", - "Argument: %s, Given: %s, Choices: %s": "Аргумент: %s, Дадзенае значэнне: %s, Магчымасці: %s", - "Argument check failed: %s": "Праверка аргументаў не ўдалася: %s", - "Implications failed:": "Дадзены аргумент патрабуе наступны дадатковы аргумент:", - "Not enough arguments following: %s": "Недастаткова наступных аргументаў: %s", - "Invalid JSON config file: %s": "Несапраўдны файл канфігурацыі JSON: %s", - "Path to JSON config file": "Шлях да файла канфігурацыі JSON", - "Show help": "Паказаць дапамогу", - "Show version number": "Паказаць нумар версіі", - "Did you mean %s?": "Вы мелі на ўвазе %s?" -} diff --git a/node_modules/webpack/node_modules/yargs/locales/de.json b/node_modules/webpack/node_modules/yargs/locales/de.json deleted file mode 100644 index d805710b0..000000000 --- a/node_modules/webpack/node_modules/yargs/locales/de.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "Commands:": "Kommandos:", - "Options:": "Optionen:", - "Examples:": "Beispiele:", - "boolean": "boolean", - "count": "Zähler", - "string": "string", - "number": "Zahl", - "array": "array", - "required": "erforderlich", - "default:": "Standard:", - "choices:": "Möglichkeiten:", - "aliases:": "Aliase:", - "generated-value": "Generierter-Wert", - "Not enough non-option arguments: got %s, need at least %s": "Nicht genügend Argumente ohne Optionen: %s vorhanden, mindestens %s benötigt", - "Too many non-option arguments: got %s, maximum of %s": "Zu viele Argumente ohne Optionen: %s vorhanden, maximal %s erlaubt", - "Missing argument value: %s": { - "one": "Fehlender Argumentwert: %s", - "other": "Fehlende Argumentwerte: %s" - }, - "Missing required argument: %s": { - "one": "Fehlendes Argument: %s", - "other": "Fehlende Argumente: %s" - }, - "Unknown argument: %s": { - "one": "Unbekanntes Argument: %s", - "other": "Unbekannte Argumente: %s" - }, - "Invalid values:": "Unzulässige Werte:", - "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Gegeben: %s, Möglichkeiten: %s", - "Argument check failed: %s": "Argumente-Check fehlgeschlagen: %s", - "Implications failed:": "Implikationen fehlgeschlagen:", - "Not enough arguments following: %s": "Nicht genügend Argumente nach: %s", - "Invalid JSON config file: %s": "Fehlerhafte JSON-Config Datei: %s", - "Path to JSON config file": "Pfad zur JSON-Config Datei", - "Show help": "Hilfe anzeigen", - "Show version number": "Version anzeigen", - "Did you mean %s?": "Meintest du %s?" -} diff --git a/node_modules/webpack/node_modules/yargs/locales/en.json b/node_modules/webpack/node_modules/yargs/locales/en.json deleted file mode 100644 index 4a618e705..000000000 --- a/node_modules/webpack/node_modules/yargs/locales/en.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "Commands:": "Commands:", - "Options:": "Options:", - "Examples:": "Examples:", - "boolean": "boolean", - "count": "count", - "string": "string", - "number": "number", - "array": "array", - "required": "required", - "default:": "default:", - "choices:": "choices:", - "aliases:": "aliases:", - "generated-value": "generated-value", - "Not enough non-option arguments: got %s, need at least %s": "Not enough non-option arguments: got %s, need at least %s", - "Too many non-option arguments: got %s, maximum of %s": "Too many non-option arguments: got %s, maximum of %s", - "Missing argument value: %s": { - "one": "Missing argument value: %s", - "other": "Missing argument values: %s" - }, - "Missing required argument: %s": { - "one": "Missing required argument: %s", - "other": "Missing required arguments: %s" - }, - "Unknown argument: %s": { - "one": "Unknown argument: %s", - "other": "Unknown arguments: %s" - }, - "Invalid values:": "Invalid values:", - "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Given: %s, Choices: %s", - "Argument check failed: %s": "Argument check failed: %s", - "Implications failed:": "Implications failed:", - "Not enough arguments following: %s": "Not enough arguments following: %s", - "Invalid JSON config file: %s": "Invalid JSON config file: %s", - "Path to JSON config file": "Path to JSON config file", - "Show help": "Show help", - "Show version number": "Show version number", - "Did you mean %s?": "Did you mean %s?", - "Arguments %s and %s are mutually exclusive" : "Arguments %s and %s are mutually exclusive" -} diff --git a/node_modules/webpack/node_modules/yargs/locales/es.json b/node_modules/webpack/node_modules/yargs/locales/es.json deleted file mode 100644 index d7c8af9f8..000000000 --- a/node_modules/webpack/node_modules/yargs/locales/es.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "Commands:": "Comandos:", - "Options:": "Opciones:", - "Examples:": "Ejemplos:", - "boolean": "booleano", - "count": "cuenta", - "string": "cadena de caracteres", - "number": "número", - "array": "tabla", - "required": "requerido", - "default:": "defecto:", - "choices:": "selección:", - "aliases:": "alias:", - "generated-value": "valor-generado", - "Not enough non-option arguments: got %s, need at least %s": "Hacen falta argumentos no-opcionales: Número recibido %s, necesita por lo menos %s", - "Too many non-option arguments: got %s, maximum of %s": "Demasiados argumentos no-opcionales: Número recibido %s, máximo es %s", - "Missing argument value: %s": { - "one": "Falta argumento: %s", - "other": "Faltan argumentos: %s" - }, - "Missing required argument: %s": { - "one": "Falta argumento requerido: %s", - "other": "Faltan argumentos requeridos: %s" - }, - "Unknown argument: %s": { - "one": "Argumento desconocido: %s", - "other": "Argumentos desconocidos: %s" - }, - "Invalid values:": "Valores inválidos:", - "Argument: %s, Given: %s, Choices: %s": "Argumento: %s, Recibido: %s, Seleccionados: %s", - "Argument check failed: %s": "Verificación de argumento ha fallado: %s", - "Implications failed:": "Implicaciones fallidas:", - "Not enough arguments following: %s": "No hay suficientes argumentos después de: %s", - "Invalid JSON config file: %s": "Archivo de configuración JSON inválido: %s", - "Path to JSON config file": "Ruta al archivo de configuración JSON", - "Show help": "Muestra ayuda", - "Show version number": "Muestra número de versión", - "Did you mean %s?": "Quisiste decir %s?" -} diff --git a/node_modules/webpack/node_modules/yargs/locales/fr.json b/node_modules/webpack/node_modules/yargs/locales/fr.json deleted file mode 100644 index 481f47e37..000000000 --- a/node_modules/webpack/node_modules/yargs/locales/fr.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "Commands:": "Commandes:", - "Options:": "Options:", - "Examples:": "Exemples:", - "boolean": "booléen", - "count": "comptage", - "string": "chaine de caractère", - "number": "nombre", - "array": "tableau", - "required": "requis", - "default:": "défaut:", - "choices:": "choix:", - "generated-value": "valeur générée", - "Not enough non-option arguments: got %s, need at least %s": "Pas assez d'arguments non-option: reçu %s, besoin d'au moins %s", - "Too many non-option arguments: got %s, maximum of %s": "Trop d'arguments non-option: reçu %s, maximum %s", - "Missing argument value: %s": { - "one": "Argument manquant: %s", - "other": "Arguments manquants: %s" - }, - "Missing required argument: %s": { - "one": "Argument requis manquant: %s", - "other": "Arguments requis manquants: %s" - }, - "Unknown argument: %s": { - "one": "Argument inconnu: %s", - "other": "Arguments inconnus: %s" - }, - "Invalid values:": "Valeurs invalides:", - "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Donné: %s, Choix: %s", - "Argument check failed: %s": "Echec de la vérification de l'argument: %s", - "Implications failed:": "Implications échouées:", - "Not enough arguments following: %s": "Pas assez d'arguments suivant: %s", - "Invalid JSON config file: %s": "Fichier de configuration JSON invalide: %s", - "Path to JSON config file": "Chemin du fichier de configuration JSON", - "Show help": "Affiche de l'aide", - "Show version number": "Affiche le numéro de version" -} diff --git a/node_modules/webpack/node_modules/yargs/locales/hi.json b/node_modules/webpack/node_modules/yargs/locales/hi.json deleted file mode 100644 index 2a9826d96..000000000 --- a/node_modules/webpack/node_modules/yargs/locales/hi.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "Commands:": "आदेश:", - "Options:": "विकल्प:", - "Examples:": "उदाहरण:", - "boolean": "सत्यता", - "count": "संख्या", - "string": "वर्णों का तार ", - "number": "अंक", - "array": "सरणी", - "required": "आवश्यक", - "default:": "डिफॉल्ट:", - "choices:": "विकल्प:", - "aliases:": "उपनाम:", - "generated-value": "उत्पन्न-मूल्य", - "Not enough non-option arguments: got %s, need at least %s": "पर्याप्त गैर-विकल्प तर्क प्राप्त नहीं: %s प्राप्त, कम से कम %s की आवश्यकता है", - "Too many non-option arguments: got %s, maximum of %s": "बहुत सारे गैर-विकल्प तर्क: %s प्राप्त, अधिकतम %s मान्य", - "Missing argument value: %s": { - "one": "कुछ तर्को के मूल्य गुम हैं: %s", - "other": "कुछ तर्को के मूल्य गुम हैं: %s" - }, - "Missing required argument: %s": { - "one": "आवश्यक तर्क गुम हैं: %s", - "other": "आवश्यक तर्क गुम हैं: %s" - }, - "Unknown argument: %s": { - "one": "अज्ञात तर्क प्राप्त: %s", - "other": "अज्ञात तर्क प्राप्त: %s" - }, - "Invalid values:": "अमान्य मूल्य:", - "Argument: %s, Given: %s, Choices: %s": "तर्क: %s, प्राप्त: %s, विकल्प: %s", - "Argument check failed: %s": "तर्क जांच विफल: %s", - "Implications failed:": "दिए गए तर्क के लिए अतिरिक्त तर्क की अपेक्षा है:", - "Not enough arguments following: %s": "निम्नलिखित के बाद पर्याप्त तर्क नहीं प्राप्त: %s", - "Invalid JSON config file: %s": "अमान्य JSON config फाइल: %s", - "Path to JSON config file": "JSON config फाइल का पथ", - "Show help": "सहायता दिखाएँ", - "Show version number": "Version संख्या दिखाएँ", - "Did you mean %s?": "क्या आपका मतलब है %s?" -} diff --git a/node_modules/webpack/node_modules/yargs/locales/hu.json b/node_modules/webpack/node_modules/yargs/locales/hu.json deleted file mode 100644 index 7b7d16606..000000000 --- a/node_modules/webpack/node_modules/yargs/locales/hu.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "Commands:": "Parancsok:", - "Options:": "Opciók:", - "Examples:": "Példák:", - "boolean": "boolean", - "count": "számláló", - "string": "szöveg", - "number": "szám", - "array": "tömb", - "required": "kötelező", - "default:": "alapértelmezett:", - "choices:": "lehetőségek:", - "aliases:": "aliaszok:", - "generated-value": "generált-érték", - "Not enough non-option arguments: got %s, need at least %s": "Nincs elég nem opcionális argumentum: %s van, legalább %s kell", - "Too many non-option arguments: got %s, maximum of %s": "Túl sok nem opciánlis argumentum van: %s van, maximum %s lehet", - "Missing argument value: %s": { - "one": "Hiányzó argumentum érték: %s", - "other": "Hiányzó argumentum értékek: %s" - }, - "Missing required argument: %s": { - "one": "Hiányzó kötelező argumentum: %s", - "other": "Hiányzó kötelező argumentumok: %s" - }, - "Unknown argument: %s": { - "one": "Ismeretlen argumentum: %s", - "other": "Ismeretlen argumentumok: %s" - }, - "Invalid values:": "Érvénytelen érték:", - "Argument: %s, Given: %s, Choices: %s": "Argumentum: %s, Megadott: %s, Lehetőségek: %s", - "Argument check failed: %s": "Argumentum ellenőrzés sikertelen: %s", - "Implications failed:": "Implikációk sikertelenek:", - "Not enough arguments following: %s": "Nem elég argumentum követi: %s", - "Invalid JSON config file: %s": "Érvénytelen JSON konfigurációs file: %s", - "Path to JSON config file": "JSON konfigurációs file helye", - "Show help": "Súgo megjelenítése", - "Show version number": "Verziószám megjelenítése", - "Did you mean %s?": "Erre gondoltál %s?" -} diff --git a/node_modules/webpack/node_modules/yargs/locales/id.json b/node_modules/webpack/node_modules/yargs/locales/id.json deleted file mode 100644 index a06e8608d..000000000 --- a/node_modules/webpack/node_modules/yargs/locales/id.json +++ /dev/null @@ -1,40 +0,0 @@ - -{ - "Commands:": "Perintah:", - "Options:": "Pilihan:", - "Examples:": "Contoh:", - "boolean": "boolean", - "count": "jumlah", - "number": "nomor", - "string": "string", - "array": "larik", - "required": "diperlukan", - "default:": "bawaan:", - "aliases:": "istilah lain:", - "choices:": "pilihan:", - "generated-value": "nilai-yang-dihasilkan", - "Not enough non-option arguments: got %s, need at least %s": "Argumen wajib kurang: hanya %s, minimal %s", - "Too many non-option arguments: got %s, maximum of %s": "Terlalu banyak argumen wajib: ada %s, maksimal %s", - "Missing argument value: %s": { - "one": "Kurang argumen: %s", - "other": "Kurang argumen: %s" - }, - "Missing required argument: %s": { - "one": "Kurang argumen wajib: %s", - "other": "Kurang argumen wajib: %s" - }, - "Unknown argument: %s": { - "one": "Argumen tak diketahui: %s", - "other": "Argumen tak diketahui: %s" - }, - "Invalid values:": "Nilai-nilai tidak valid:", - "Argument: %s, Given: %s, Choices: %s": "Argumen: %s, Diberikan: %s, Pilihan: %s", - "Argument check failed: %s": "Pemeriksaan argument gagal: %s", - "Implications failed:": "Implikasi gagal:", - "Not enough arguments following: %s": "Kurang argumen untuk: %s", - "Invalid JSON config file: %s": "Berkas konfigurasi JSON tidak valid: %s", - "Path to JSON config file": "Alamat berkas konfigurasi JSON", - "Show help": "Lihat bantuan", - "Show version number": "Lihat nomor versi", - "Did you mean %s?": "Maksud Anda: %s?" -} diff --git a/node_modules/webpack/node_modules/yargs/locales/it.json b/node_modules/webpack/node_modules/yargs/locales/it.json deleted file mode 100644 index f9eb3756e..000000000 --- a/node_modules/webpack/node_modules/yargs/locales/it.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "Commands:": "Comandi:", - "Options:": "Opzioni:", - "Examples:": "Esempi:", - "boolean": "booleano", - "count": "contatore", - "string": "stringa", - "number": "numero", - "array": "vettore", - "required": "richiesto", - "default:": "predefinito:", - "choices:": "scelte:", - "aliases:": "alias:", - "generated-value": "valore generato", - "Not enough non-option arguments: got %s, need at least %s": "Numero insufficiente di argomenti non opzione: inseriti %s, richiesti almeno %s", - "Too many non-option arguments: got %s, maximum of %s": "Troppi argomenti non opzione: inseriti %s, massimo possibile %s", - "Missing argument value: %s": { - "one": "Argomento mancante: %s", - "other": "Argomenti mancanti: %s" - }, - "Missing required argument: %s": { - "one": "Argomento richiesto mancante: %s", - "other": "Argomenti richiesti mancanti: %s" - }, - "Unknown argument: %s": { - "one": "Argomento sconosciuto: %s", - "other": "Argomenti sconosciuti: %s" - }, - "Invalid values:": "Valori non validi:", - "Argument: %s, Given: %s, Choices: %s": "Argomento: %s, Richiesto: %s, Scelte: %s", - "Argument check failed: %s": "Controllo dell'argomento fallito: %s", - "Implications failed:": "Argomenti impliciti non soddisfatti:", - "Not enough arguments following: %s": "Argomenti insufficienti dopo: %s", - "Invalid JSON config file: %s": "File di configurazione JSON non valido: %s", - "Path to JSON config file": "Percorso del file di configurazione JSON", - "Show help": "Mostra la schermata di aiuto", - "Show version number": "Mostra il numero di versione", - "Did you mean %s?": "Intendi forse %s?" -} diff --git a/node_modules/webpack/node_modules/yargs/locales/ja.json b/node_modules/webpack/node_modules/yargs/locales/ja.json deleted file mode 100644 index 45a64a812..000000000 --- a/node_modules/webpack/node_modules/yargs/locales/ja.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "Commands:": "コマンド:", - "Options:": "オプション:", - "Examples:": "例:", - "boolean": "真偽", - "count": "カウント", - "string": "文字列", - "number": "数値", - "array": "配列", - "required": "必須", - "default:": "デフォルト:", - "choices:": "選択してください:", - "aliases:": "エイリアス:", - "generated-value": "生成された値", - "Not enough non-option arguments: got %s, need at least %s": "オプションではない引数が %s 個では不足しています。少なくとも %s 個の引数が必要です:", - "Too many non-option arguments: got %s, maximum of %s": "オプションではない引数が %s 個では多すぎます。最大で %s 個までです:", - "Missing argument value: %s": { - "one": "引数が見つかりません: %s", - "other": "引数が見つかりません: %s" - }, - "Missing required argument: %s": { - "one": "必須の引数が見つかりません: %s", - "other": "必須の引数が見つかりません: %s" - }, - "Unknown argument: %s": { - "one": "未知の引数です: %s", - "other": "未知の引数です: %s" - }, - "Invalid values:": "不正な値です:", - "Argument: %s, Given: %s, Choices: %s": "引数は %s です。指定できるのは %s つです。選択してください: %s", - "Argument check failed: %s": "引数のチェックに失敗しました: %s", - "Implications failed:": "オプションの組み合わせで不正が生じました:", - "Not enough arguments following: %s": "次の引数が不足しています。: %s", - "Invalid JSON config file: %s": "JSONの設定ファイルが不正です: %s", - "Path to JSON config file": "JSONの設定ファイルまでのpath", - "Show help": "ヘルプを表示", - "Show version number": "バージョンを表示", - "Did you mean %s?": "もしかして %s?" -} diff --git a/node_modules/webpack/node_modules/yargs/locales/ko.json b/node_modules/webpack/node_modules/yargs/locales/ko.json deleted file mode 100644 index e71498479..000000000 --- a/node_modules/webpack/node_modules/yargs/locales/ko.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "Commands:": "명령:", - "Options:": "옵션:", - "Examples:": "예시:", - "boolean": "여부", - "count": "개수", - "string": "문자열", - "number": "숫자", - "array": "배열", - "required": "필수", - "default:": "기본:", - "choices:": "선택:", - "aliases:": "별칭:", - "generated-value": "생성된 값", - "Not enough non-option arguments: got %s, need at least %s": "옵션이 아닌 인자가 충분치 않습니다: %s개를 받았지만, 적어도 %s개는 필요합니다", - "Too many non-option arguments: got %s, maximum of %s": "옵션이 아닌 인자가 너무 많습니다: %s개를 받았지만, %s개 이하여야 합니다", - "Missing argument value: %s": { - "one": "인자값을 받지 못했습니다: %s", - "other": "인자값들을 받지 못했습니다: %s" - }, - "Missing required argument: %s": { - "one": "필수 인자를 받지 못했습니다: %s", - "other": "필수 인자들을 받지 못했습니다: %s" - }, - "Unknown argument: %s": { - "one": "알 수 없는 인자입니다: %s", - "other": "알 수 없는 인자들입니다: %s" - }, - "Invalid values:": "잘못된 값입니다:", - "Argument: %s, Given: %s, Choices: %s": "인자: %s, 입력받은 값: %s, 선택지: %s", - "Argument check failed: %s": "유효하지 않은 인자입니다: %s", - "Implications failed:": "옵션의 조합이 잘못되었습니다:", - "Not enough arguments following: %s": "인자가 충분하게 주어지지 않았습니다: %s", - "Invalid JSON config file: %s": "유효하지 않은 JSON 설정파일입니다: %s", - "Path to JSON config file": "JSON 설정파일 경로", - "Show help": "도움말을 보여줍니다", - "Show version number": "버전 넘버를 보여줍니다", - "Did you mean %s?": "찾고계신게 %s입니까?" -} diff --git a/node_modules/webpack/node_modules/yargs/locales/nb.json b/node_modules/webpack/node_modules/yargs/locales/nb.json deleted file mode 100644 index fc607fb1e..000000000 --- a/node_modules/webpack/node_modules/yargs/locales/nb.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "Commands:": "Kommandoer:", - "Options:": "Alternativer:", - "Examples:": "Eksempler:", - "boolean": "boolsk", - "count": "antall", - "string": "streng", - "number": "nummer", - "array": "matrise", - "required": "obligatorisk", - "default:": "standard:", - "choices:": "valg:", - "generated-value": "generert-verdi", - "Not enough non-option arguments: got %s, need at least %s": "Ikke nok ikke-alternativ argumenter: fikk %s, trenger minst %s", - "Too many non-option arguments: got %s, maximum of %s": "For mange ikke-alternativ argumenter: fikk %s, maksimum %s", - "Missing argument value: %s": { - "one": "Mangler argument verdi: %s", - "other": "Mangler argument verdier: %s" - }, - "Missing required argument: %s": { - "one": "Mangler obligatorisk argument: %s", - "other": "Mangler obligatoriske argumenter: %s" - }, - "Unknown argument: %s": { - "one": "Ukjent argument: %s", - "other": "Ukjente argumenter: %s" - }, - "Invalid values:": "Ugyldige verdier:", - "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Gitt: %s, Valg: %s", - "Argument check failed: %s": "Argument sjekk mislyktes: %s", - "Implications failed:": "Konsekvensene mislyktes:", - "Not enough arguments following: %s": "Ikke nok følgende argumenter: %s", - "Invalid JSON config file: %s": "Ugyldig JSON konfigurasjonsfil: %s", - "Path to JSON config file": "Bane til JSON konfigurasjonsfil", - "Show help": "Vis hjelp", - "Show version number": "Vis versjonsnummer" -} diff --git a/node_modules/webpack/node_modules/yargs/locales/nl.json b/node_modules/webpack/node_modules/yargs/locales/nl.json deleted file mode 100644 index fc029dbeb..000000000 --- a/node_modules/webpack/node_modules/yargs/locales/nl.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "Commands:": "Opdrachten:", - "Options:": "Opties:", - "Examples:": "Voorbeelden:", - "boolean": "boolean", - "count": "aantal", - "string": "text", - "number": "nummer", - "array": "lijst", - "required": "verplicht", - "default:": "standaard:", - "choices:": "keuzes:", - "aliases:": "aliassen:", - "generated-value": "gegenereerde waarde", - "Not enough non-option arguments: got %s, need at least %s": "Niet genoeg non-optie argumenten. Gekregen: %s, minstens nodig: %s", - "Too many non-option arguments: got %s, maximum of %s": "Te veel non-optie argumenten. Gekregen: %s, maximum: %s", - "Missing argument value: %s": { - "one": "Missing argument value: %s", - "other": "Missing argument values: %s" - }, - "Missing required argument: %s": { - "one": "Missend verplichte argument: %s", - "other": "Missende verplichte argumenten: %s" - }, - "Unknown argument: %s": { - "one": "Onbekend argument: %s", - "other": "Onbekende argumenten: %s" - }, - "Invalid values:": "Ongeldige waardes:", - "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Gegeven: %s, Keuzes: %s", - "Argument check failed: %s": "Argument check mislukt: %s", - "Implications failed:": "Implicaties mislukt:", - "Not enough arguments following: %s": "Niet genoeg argumenten na: %s", - "Invalid JSON config file: %s": "Ongeldig JSON configuratiebestand: %s", - "Path to JSON config file": "Pad naar JSON configuratiebestand", - "Show help": "Toon help", - "Show version number": "Toon versie nummer", - "Did you mean %s?": "Bedoelde u misschien %s?" -} diff --git a/node_modules/webpack/node_modules/yargs/locales/pirate.json b/node_modules/webpack/node_modules/yargs/locales/pirate.json deleted file mode 100644 index 1f4e19e65..000000000 --- a/node_modules/webpack/node_modules/yargs/locales/pirate.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "Commands:": "Choose yer command:", - "Options:": "Options for me hearties!", - "Examples:": "Ex. marks the spot:", - "required": "requi-yar-ed", - "Missing required argument: %s": { - "one": "Ye be havin' to set the followin' argument land lubber: %s", - "other": "Ye be havin' to set the followin' arguments land lubber: %s" - }, - "Show help": "Parlay this here code of conduct", - "Show version number": "'Tis the version ye be askin' fer" -} diff --git a/node_modules/webpack/node_modules/yargs/locales/pl.json b/node_modules/webpack/node_modules/yargs/locales/pl.json deleted file mode 100644 index 1c834f693..000000000 --- a/node_modules/webpack/node_modules/yargs/locales/pl.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "Commands:": "Polecenia:", - "Options:": "Opcje:", - "Examples:": "Przykłady:", - "boolean": "boolean", - "count": "ilość", - "string": "ciąg znaków", - "number": "liczba", - "array": "tablica", - "required": "wymagany", - "default:": "domyślny:", - "choices:": "dostępne:", - "aliases:": "aliasy:", - "generated-value": "wygenerowana-wartość", - "Not enough non-option arguments: got %s, need at least %s": "Niewystarczająca ilość argumentów: otrzymano %s, wymagane co najmniej %s", - "Too many non-option arguments: got %s, maximum of %s": "Zbyt duża ilość argumentów: otrzymano %s, wymagane co najwyżej %s", - "Missing argument value: %s": { - "one": "Brak wartości dla argumentu: %s", - "other": "Brak wartości dla argumentów: %s" - }, - "Missing required argument: %s": { - "one": "Brak wymaganego argumentu: %s", - "other": "Brak wymaganych argumentów: %s" - }, - "Unknown argument: %s": { - "one": "Nieznany argument: %s", - "other": "Nieznane argumenty: %s" - }, - "Invalid values:": "Nieprawidłowe wartości:", - "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Otrzymano: %s, Dostępne: %s", - "Argument check failed: %s": "Weryfikacja argumentów nie powiodła się: %s", - "Implications failed:": "Założenia nie zostały spełnione:", - "Not enough arguments following: %s": "Niewystarczająca ilość argumentów następujących po: %s", - "Invalid JSON config file: %s": "Nieprawidłowy plik konfiguracyjny JSON: %s", - "Path to JSON config file": "Ścieżka do pliku konfiguracyjnego JSON", - "Show help": "Pokaż pomoc", - "Show version number": "Pokaż numer wersji", - "Did you mean %s?": "Czy chodziło Ci o %s?" -} diff --git a/node_modules/webpack/node_modules/yargs/locales/pt.json b/node_modules/webpack/node_modules/yargs/locales/pt.json deleted file mode 100644 index 75c3921c8..000000000 --- a/node_modules/webpack/node_modules/yargs/locales/pt.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "Commands:": "Comandos:", - "Options:": "Opções:", - "Examples:": "Exemplos:", - "boolean": "boolean", - "count": "contagem", - "string": "cadeia de caracteres", - "number": "número", - "array": "arranjo", - "required": "requerido", - "default:": "padrão:", - "choices:": "escolhas:", - "generated-value": "valor-gerado", - "Not enough non-option arguments: got %s, need at least %s": "Argumentos insuficientes não opcionais: Argumento %s, necessário pelo menos %s", - "Too many non-option arguments: got %s, maximum of %s": "Excesso de argumentos não opcionais: recebido %s, máximo de %s", - "Missing argument value: %s": { - "one": "Falta valor de argumento: %s", - "other": "Falta valores de argumento: %s" - }, - "Missing required argument: %s": { - "one": "Falta argumento obrigatório: %s", - "other": "Faltando argumentos obrigatórios: %s" - }, - "Unknown argument: %s": { - "one": "Argumento desconhecido: %s", - "other": "Argumentos desconhecidos: %s" - }, - "Invalid values:": "Valores inválidos:", - "Argument: %s, Given: %s, Choices: %s": "Argumento: %s, Dado: %s, Escolhas: %s", - "Argument check failed: %s": "Verificação de argumento falhou: %s", - "Implications failed:": "Implicações falharam:", - "Not enough arguments following: %s": "Insuficientes argumentos a seguir: %s", - "Invalid JSON config file: %s": "Arquivo de configuração em JSON esta inválido: %s", - "Path to JSON config file": "Caminho para o arquivo de configuração em JSON", - "Show help": "Mostra ajuda", - "Show version number": "Mostra número de versão", - "Arguments %s and %s are mutually exclusive" : "Argumentos %s e %s são mutualmente exclusivos" -} diff --git a/node_modules/webpack/node_modules/yargs/locales/pt_BR.json b/node_modules/webpack/node_modules/yargs/locales/pt_BR.json deleted file mode 100644 index 60e5ffa24..000000000 --- a/node_modules/webpack/node_modules/yargs/locales/pt_BR.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "Commands:": "Comandos:", - "Options:": "Opções:", - "Examples:": "Exemplos:", - "boolean": "boolean", - "count": "contagem", - "string": "string", - "number": "número", - "array": "array", - "required": "obrigatório", - "default:": "padrão:", - "choices:": "opções:", - "aliases:": "sinônimos:", - "generated-value": "valor-gerado", - "Not enough non-option arguments: got %s, need at least %s": "Argumentos insuficientes: Argumento %s, necessário pelo menos %s", - "Too many non-option arguments: got %s, maximum of %s": "Excesso de argumentos: recebido %s, máximo de %s", - "Missing argument value: %s": { - "one": "Falta valor de argumento: %s", - "other": "Falta valores de argumento: %s" - }, - "Missing required argument: %s": { - "one": "Falta argumento obrigatório: %s", - "other": "Faltando argumentos obrigatórios: %s" - }, - "Unknown argument: %s": { - "one": "Argumento desconhecido: %s", - "other": "Argumentos desconhecidos: %s" - }, - "Invalid values:": "Valores inválidos:", - "Argument: %s, Given: %s, Choices: %s": "Argumento: %s, Dado: %s, Opções: %s", - "Argument check failed: %s": "Verificação de argumento falhou: %s", - "Implications failed:": "Implicações falharam:", - "Not enough arguments following: %s": "Argumentos insuficientes a seguir: %s", - "Invalid JSON config file: %s": "Arquivo JSON de configuração inválido: %s", - "Path to JSON config file": "Caminho para o arquivo JSON de configuração", - "Show help": "Exibe ajuda", - "Show version number": "Exibe a versão", - "Did you mean %s?": "Você quis dizer %s?", - "Arguments %s and %s are mutually exclusive" : "Argumentos %s e %s são mutualmente exclusivos" -} diff --git a/node_modules/webpack/node_modules/yargs/locales/ru.json b/node_modules/webpack/node_modules/yargs/locales/ru.json deleted file mode 100644 index cb7b88b49..000000000 --- a/node_modules/webpack/node_modules/yargs/locales/ru.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "Commands:": "Команды:", - "Options:": "Опции:", - "Examples:": "Примеры:", - "boolean": "булевый тип", - "count": "подсчет", - "string": "строковой тип", - "number": "число", - "array": "массив", - "required": "необходимо", - "default:": "по умолчанию:", - "choices:": "возможности:", - "aliases:": "алиасы:", - "generated-value": "генерированное значение", - "Not enough non-option arguments: got %s, need at least %s": "Недостаточно неопционных аргументов: есть %s, нужно как минимум %s", - "Too many non-option arguments: got %s, maximum of %s": "Слишком много неопционных аргументов: есть %s, максимум допустимо %s", - "Missing argument value: %s": { - "one": "Не хватает значения аргумента: %s", - "other": "Не хватает значений аргументов: %s" - }, - "Missing required argument: %s": { - "one": "Не хватает необходимого аргумента: %s", - "other": "Не хватает необходимых аргументов: %s" - }, - "Unknown argument: %s": { - "one": "Неизвестный аргумент: %s", - "other": "Неизвестные аргументы: %s" - }, - "Invalid values:": "Недействительные значения:", - "Argument: %s, Given: %s, Choices: %s": "Аргумент: %s, Данное значение: %s, Возможности: %s", - "Argument check failed: %s": "Проверка аргументов не удалась: %s", - "Implications failed:": "Данный аргумент требует следующий дополнительный аргумент:", - "Not enough arguments following: %s": "Недостаточно следующих аргументов: %s", - "Invalid JSON config file: %s": "Недействительный файл конфигурации JSON: %s", - "Path to JSON config file": "Путь к файлу конфигурации JSON", - "Show help": "Показать помощь", - "Show version number": "Показать номер версии", - "Did you mean %s?": "Вы имели в виду %s?" -} diff --git a/node_modules/webpack/node_modules/yargs/locales/th.json b/node_modules/webpack/node_modules/yargs/locales/th.json deleted file mode 100644 index 3f08dcd23..000000000 --- a/node_modules/webpack/node_modules/yargs/locales/th.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "Commands:": "คอมมาน", - "Options:": "ออฟชั่น", - "Examples:": "ตัวอย่าง", - "boolean": "บูลีน", - "count": "นับ", - "string": "สตริง", - "number": "ตัวเลข", - "array": "อาเรย์", - "required": "จำเป็น", - "default:": "ค่าเริ่มต้น", - "choices:": "ตัวเลือก", - "aliases:": "เอเลียส", - "generated-value": "ค่าที่ถูกสร้างขึ้น", - "Not enough non-option arguments: got %s, need at least %s": "ใส่อาร์กิวเมนต์ไม่ครบตามจำนวนที่กำหนด: ใส่ค่ามาจำนวน %s ค่า, แต่ต้องการอย่างน้อย %s ค่า", - "Too many non-option arguments: got %s, maximum of %s": "ใส่อาร์กิวเมนต์เกินจำนวนที่กำหนด: ใส่ค่ามาจำนวน %s ค่า, แต่ต้องการมากที่สุด %s ค่า", - "Missing argument value: %s": { - "one": "ค่าอาร์กิวเมนต์ที่ขาดไป: %s", - "other": "ค่าอาร์กิวเมนต์ที่ขาดไป: %s" - }, - "Missing required argument: %s": { - "one": "อาร์กิวเมนต์จำเป็นที่ขาดไป: %s", - "other": "อาร์กิวเมนต์จำเป็นที่ขาดไป: %s" - }, - "Unknown argument: %s": { - "one": "อาร์กิวเมนต์ที่ไม่รู้จัก: %s", - "other": "อาร์กิวเมนต์ที่ไม่รู้จัก: %s" - }, - "Invalid values:": "ค่าไม่ถูกต้อง:", - "Argument: %s, Given: %s, Choices: %s": "อาร์กิวเมนต์: %s, ได้รับ: %s, ตัวเลือก: %s", - "Argument check failed: %s": "ตรวจสอบพบอาร์กิวเมนต์ที่ไม่ถูกต้อง: %s", - "Implications failed:": "Implications ไม่สำเร็จ:", - "Not enough arguments following: %s": "ใส่อาร์กิวเมนต์ไม่ครบ: %s", - "Invalid JSON config file: %s": "ไฟล์คอนฟิค JSON ไม่ถูกต้อง: %s", - "Path to JSON config file": "พาทไฟล์คอนฟิค JSON", - "Show help": "ขอความช่วยเหลือ", - "Show version number": "แสดงตัวเลขเวอร์ชั่น", - "Did you mean %s?": "คุณหมายถึง %s?" -} diff --git a/node_modules/webpack/node_modules/yargs/locales/tr.json b/node_modules/webpack/node_modules/yargs/locales/tr.json deleted file mode 100644 index 000060b91..000000000 --- a/node_modules/webpack/node_modules/yargs/locales/tr.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "Commands:": "Komutlar:", - "Options:": "Seçenekler:", - "Examples:": "Örnekler:", - "boolean": "boolean", - "count": "sayı", - "string": "string", - "number": "numara", - "array": "array", - "required": "zorunlu", - "default:": "varsayılan:", - "choices:": "seçimler:", - "aliases:": "takma adlar:", - "generated-value": "oluşturulan-değer", - "Not enough non-option arguments: got %s, need at least %s": "Seçenek dışı argümanlar yetersiz: %s bulundu, %s gerekli", - "Too many non-option arguments: got %s, maximum of %s": "Seçenek dışı argümanlar gereğinden fazla: %s bulundu, azami %s", - "Missing argument value: %s": { - "one": "Eksik argüman değeri: %s", - "other": "Eksik argüman değerleri: %s" - }, - "Missing required argument: %s": { - "one": "Eksik zorunlu argüman: %s", - "other": "Eksik zorunlu argümanlar: %s" - }, - "Unknown argument: %s": { - "one": "Bilinmeyen argüman: %s", - "other": "Bilinmeyen argümanlar: %s" - }, - "Invalid values:": "Geçersiz değerler:", - "Argument: %s, Given: %s, Choices: %s": "Argüman: %s, Verilen: %s, Seçimler: %s", - "Argument check failed: %s": "Argüman kontrolü başarısız oldu: %s", - "Implications failed:": "Sonuçlar başarısız oldu:", - "Not enough arguments following: %s": "%s için yeterli argüman bulunamadı", - "Invalid JSON config file: %s": "Geçersiz JSON yapılandırma dosyası: %s", - "Path to JSON config file": "JSON yapılandırma dosya konumu", - "Show help": "Yardım detaylarını göster", - "Show version number": "Versiyon detaylarını göster", - "Did you mean %s?": "Bunu mu demek istediniz: %s?" -} diff --git a/node_modules/webpack/node_modules/yargs/locales/zh_CN.json b/node_modules/webpack/node_modules/yargs/locales/zh_CN.json deleted file mode 100644 index b25c7b9d2..000000000 --- a/node_modules/webpack/node_modules/yargs/locales/zh_CN.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "Commands:": "命令:", - "Options:": "选项:", - "Examples:": "示例:", - "boolean": "布尔", - "count": "计数", - "string": "字符串", - "number": "数字", - "array": "数组", - "required": "必需", - "default:": "默认值:", - "choices:": "可选值:", - "generated-value": "生成的值", - "Not enough non-option arguments: got %s, need at least %s": "缺少 non-option 参数:传入了 %s 个, 至少需要 %s 个", - "Too many non-option arguments: got %s, maximum of %s": "non-option 参数过多:传入了 %s 个, 最大允许 %s 个", - "Missing argument value: %s": { - "one": "没有给此选项指定值:%s", - "other": "没有给这些选项指定值:%s" - }, - "Missing required argument: %s": { - "one": "缺少必须的选项:%s", - "other": "缺少这些必须的选项:%s" - }, - "Unknown argument: %s": { - "one": "无法识别的选项:%s", - "other": "无法识别这些选项:%s" - }, - "Invalid values:": "无效的选项值:", - "Argument: %s, Given: %s, Choices: %s": "选项名称: %s, 传入的值: %s, 可选的值:%s", - "Argument check failed: %s": "选项值验证失败:%s", - "Implications failed:": "缺少依赖的选项:", - "Not enough arguments following: %s": "没有提供足够的值给此选项:%s", - "Invalid JSON config file: %s": "无效的 JSON 配置文件:%s", - "Path to JSON config file": "JSON 配置文件的路径", - "Show help": "显示帮助信息", - "Show version number": "显示版本号" -} diff --git a/node_modules/webpack/node_modules/yargs/locales/zh_TW.json b/node_modules/webpack/node_modules/yargs/locales/zh_TW.json deleted file mode 100644 index 12498888a..000000000 --- a/node_modules/webpack/node_modules/yargs/locales/zh_TW.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "Commands:": "命令:", - "Options:": "選項:", - "Examples:": "例:", - "boolean": "布林", - "count": "次數", - "string": "字串", - "number": "數字", - "array": "陣列", - "required": "必須", - "default:": "預設值:", - "choices:": "可選值:", - "aliases:": "別名:", - "generated-value": "生成的值", - "Not enough non-option arguments: got %s, need at least %s": "non-option 引數不足:只傳入了 %s 個, 至少要 %s 個", - "Too many non-option arguments: got %s, maximum of %s": "non-option 引數過多:傳入了 %s 個, 但最多 %s 個", - "Missing argument value: %s": { - "one": "此引數無指定值:%s", - "other": "這些引數無指定值:%s" - }, - "Missing required argument: %s": { - "one": "缺少必須的引數:%s", - "other": "缺少這些必須的引數:%s" - }, - "Unknown argument: %s": { - "one": "未知的引數:%s", - "other": "未知的這些引數:%s" - }, - "Invalid values:": "無效的選項值:", - "Argument: %s, Given: %s, Choices: %s": "引數名稱: %s, 傳入的值: %s, 可選的值:%s", - "Argument check failed: %s": "引數驗證失敗:%s", - "Implications failed:": "缺少依賴的選項:", - "Not enough arguments following: %s": "沒有提供足夠的值給此引數:%s", - "Invalid JSON config file: %s": "無效的 JSON 設置文件:%s", - "Path to JSON config file": "JSON 設置文件的路徑", - "Show help": "顯示說明", - "Show version number": "顯示版本", - "Did you mean %s?": "是指 %s?", - "Arguments %s and %s are mutually exclusive" : "引數 %s 和 %s 是互斥的" -} diff --git a/node_modules/webpack/node_modules/yargs/package.json b/node_modules/webpack/node_modules/yargs/package.json deleted file mode 100644 index c9a799f7a..000000000 --- a/node_modules/webpack/node_modules/yargs/package.json +++ /dev/null @@ -1,74 +0,0 @@ -{ - "name": "yargs", - "version": "8.0.2", - "description": "yargs the modern, pirate-themed, successor to optimist.", - "main": "./index.js", - "files": [ - "index.js", - "yargs.js", - "lib", - "locales", - "completion.sh.hbs", - "LICENSE" - ], - "dependencies": { - "camelcase": "^4.1.0", - "cliui": "^3.2.0", - "decamelize": "^1.1.1", - "get-caller-file": "^1.0.1", - "os-locale": "^2.0.0", - "read-pkg-up": "^2.0.0", - "require-directory": "^2.1.1", - "require-main-filename": "^1.0.1", - "set-blocking": "^2.0.0", - "string-width": "^2.0.0", - "which-module": "^2.0.0", - "y18n": "^3.2.1", - "yargs-parser": "^7.0.0" - }, - "devDependencies": { - "chai": "^3.4.1", - "chalk": "^1.1.3", - "coveralls": "^2.11.11", - "cpr": "^2.0.0", - "cross-spawn": "^5.0.1", - "es6-promise": "^4.0.2", - "hashish": "0.0.4", - "mocha": "^3.0.1", - "nyc": "^10.3.0", - "rimraf": "^2.5.0", - "standard": "^8.6.0", - "standard-version": "^4.2.0", - "which": "^1.2.9", - "yargs-test-extends": "^1.0.1" - }, - "scripts": { - "pretest": "standard", - "test": "nyc --cache mocha --require ./test/before.js --timeout=8000 --check-leaks", - "coverage": "nyc report --reporter=text-lcov | coveralls", - "release": "standard-version" - }, - "repository": { - "type": "git", - "url": "http://github.com/yargs/yargs.git" - }, - "homepage": "http://yargs.js.org/", - "standard": { - "ignore": [ - "**/example/**" - ] - }, - "keywords": [ - "argument", - "args", - "option", - "parser", - "parsing", - "cli", - "command" - ], - "license": "MIT", - "engine": { - "node": ">=0.10" - } -} diff --git a/node_modules/webpack/node_modules/yargs/yargs.js b/node_modules/webpack/node_modules/yargs/yargs.js deleted file mode 100644 index 078bf8f14..000000000 --- a/node_modules/webpack/node_modules/yargs/yargs.js +++ /dev/null @@ -1,1127 +0,0 @@ -const argsert = require('./lib/argsert') -const assign = require('./lib/assign') -const Command = require('./lib/command') -const Completion = require('./lib/completion') -const Parser = require('yargs-parser') -const path = require('path') -const Usage = require('./lib/usage') -const Validation = require('./lib/validation') -const Y18n = require('y18n') -const objFilter = require('./lib/obj-filter') -const setBlocking = require('set-blocking') -const applyExtends = require('./lib/apply-extends') -const YError = require('./lib/yerror') - -var exports = module.exports = Yargs -function Yargs (processArgs, cwd, parentRequire) { - processArgs = processArgs || [] // handle calling yargs(). - - const self = {} - var command = null - var completion = null - var groups = {} - var output = '' - var preservedGroups = {} - var usage = null - var validation = null - - const y18n = Y18n({ - directory: path.resolve(__dirname, './locales'), - updateFiles: false - }) - - if (!cwd) cwd = process.cwd() - - self.$0 = process.argv - .slice(0, 2) - .map(function (x, i) { - // ignore the node bin, specify this in your - // bin file with #!/usr/bin/env node - if (i === 0 && /\b(node|iojs)(\.exe)?$/.test(x)) return - var b = rebase(cwd, x) - return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x - }) - .join(' ').trim() - - if (process.env._ !== undefined && process.argv[1] === process.env._) { - self.$0 = process.env._.replace( - path.dirname(process.execPath) + '/', '' - ) - } - - // use context object to keep track of resets, subcommand execution, etc - // submodules should modify and check the state of context as necessary - const context = { resets: -1, commands: [], files: [] } - self.getContext = function () { - return context - } - - // puts yargs back into an initial state. any keys - // that have been set to "global" will not be reset - // by this action. - var options - self.resetOptions = self.reset = function (aliases) { - context.resets++ - aliases = aliases || {} - options = options || {} - // put yargs back into an initial state, this - // logic is used to build a nested command - // hierarchy. - var tmpOptions = {} - tmpOptions.local = options.local ? options.local : [] - tmpOptions.configObjects = options.configObjects ? options.configObjects : [] - - // if a key has been explicitly set as local, - // we should reset it before passing options to command. - var localLookup = {} - tmpOptions.local.forEach(function (l) { - localLookup[l] = true - ;(aliases[l] || []).forEach(function (a) { - localLookup[a] = true - }) - }) - - // preserve all groups not set to local. - preservedGroups = Object.keys(groups).reduce(function (acc, groupName) { - var keys = groups[groupName].filter(function (key) { - return !(key in localLookup) - }) - if (keys.length > 0) { - acc[groupName] = keys - } - return acc - }, {}) - // groups can now be reset - groups = {} - - var arrayOptions = [ - 'array', 'boolean', 'string', 'requiresArg', 'skipValidation', - 'count', 'normalize', 'number' - ] - - var objectOptions = [ - 'narg', 'key', 'alias', 'default', 'defaultDescription', - 'config', 'choices', 'demandedOptions', 'demandedCommands', 'coerce' - ] - - arrayOptions.forEach(function (k) { - tmpOptions[k] = (options[k] || []).filter(function (k) { - return !localLookup[k] - }) - }) - - objectOptions.forEach(function (k) { - tmpOptions[k] = objFilter(options[k], function (k, v) { - return !localLookup[k] - }) - }) - - tmpOptions.envPrefix = options.envPrefix - options = tmpOptions - - // if this is the first time being executed, create - // instances of all our helpers -- otherwise just reset. - usage = usage ? usage.reset(localLookup) : Usage(self, y18n) - validation = validation ? validation.reset(localLookup) : Validation(self, usage, y18n) - command = command ? command.reset() : Command(self, usage, validation) - if (!completion) completion = Completion(self, usage, command) - - completionCommand = null - output = '' - exitError = null - hasOutput = false - self.parsed = false - - return self - } - self.resetOptions() - - // temporary hack: allow "freezing" of reset-able state for parse(msg, cb) - var frozen - function freeze () { - frozen = {} - frozen.options = options - frozen.configObjects = options.configObjects.slice(0) - frozen.exitProcess = exitProcess - frozen.groups = groups - usage.freeze() - validation.freeze() - command.freeze() - frozen.strict = strict - frozen.completionCommand = completionCommand - frozen.output = output - frozen.exitError = exitError - frozen.hasOutput = hasOutput - frozen.parsed = self.parsed - } - function unfreeze () { - options = frozen.options - options.configObjects = frozen.configObjects - exitProcess = frozen.exitProcess - groups = frozen.groups - output = frozen.output - exitError = frozen.exitError - hasOutput = frozen.hasOutput - self.parsed = frozen.parsed - usage.unfreeze() - validation.unfreeze() - command.unfreeze() - strict = frozen.strict - completionCommand = frozen.completionCommand - parseFn = null - parseContext = null - frozen = undefined - } - - self.boolean = function (keys) { - argsert('<array|string>', [keys], arguments.length) - populateParserHintArray('boolean', keys) - return self - } - - self.array = function (keys) { - argsert('<array|string>', [keys], arguments.length) - populateParserHintArray('array', keys) - return self - } - - self.number = function (keys) { - argsert('<array|string>', [keys], arguments.length) - populateParserHintArray('number', keys) - return self - } - - self.normalize = function (keys) { - argsert('<array|string>', [keys], arguments.length) - populateParserHintArray('normalize', keys) - return self - } - - self.count = function (keys) { - argsert('<array|string>', [keys], arguments.length) - populateParserHintArray('count', keys) - return self - } - - self.string = function (keys) { - argsert('<array|string>', [keys], arguments.length) - populateParserHintArray('string', keys) - return self - } - - self.requiresArg = function (keys) { - argsert('<array|string>', [keys], arguments.length) - populateParserHintArray('requiresArg', keys) - return self - } - - self.skipValidation = function (keys) { - argsert('<array|string>', [keys], arguments.length) - populateParserHintArray('skipValidation', keys) - return self - } - - function populateParserHintArray (type, keys, value) { - keys = [].concat(keys) - keys.forEach(function (key) { - options[type].push(key) - }) - } - - self.nargs = function (key, value) { - argsert('<string|object|array> [number]', [key, value], arguments.length) - populateParserHintObject(self.nargs, false, 'narg', key, value) - return self - } - - self.choices = function (key, value) { - argsert('<object|string|array> [string|array]', [key, value], arguments.length) - populateParserHintObject(self.choices, true, 'choices', key, value) - return self - } - - self.alias = function (key, value) { - argsert('<object|string|array> [string|array]', [key, value], arguments.length) - populateParserHintObject(self.alias, true, 'alias', key, value) - return self - } - - // TODO: actually deprecate self.defaults. - self.default = self.defaults = function (key, value, defaultDescription) { - argsert('<object|string|array> [*] [string]', [key, value, defaultDescription], arguments.length) - if (defaultDescription) options.defaultDescription[key] = defaultDescription - if (typeof value === 'function') { - if (!options.defaultDescription[key]) options.defaultDescription[key] = usage.functionDescription(value) - value = value.call() - } - populateParserHintObject(self.default, false, 'default', key, value) - return self - } - - self.describe = function (key, desc) { - argsert('<object|string|array> [string]', [key, desc], arguments.length) - populateParserHintObject(self.describe, false, 'key', key, true) - usage.describe(key, desc) - return self - } - - self.demandOption = function (keys, msg) { - argsert('<object|string|array> [string]', [keys, msg], arguments.length) - populateParserHintObject(self.demandOption, false, 'demandedOptions', keys, msg) - return self - } - - self.coerce = function (keys, value) { - argsert('<object|string|array> [function]', [keys, value], arguments.length) - populateParserHintObject(self.coerce, false, 'coerce', keys, value) - return self - } - - function populateParserHintObject (builder, isArray, type, key, value) { - if (Array.isArray(key)) { - // an array of keys with one value ['x', 'y', 'z'], function parse () {} - var temp = {} - key.forEach(function (k) { - temp[k] = value - }) - builder(temp) - } else if (typeof key === 'object') { - // an object of key value pairs: {'x': parse () {}, 'y': parse() {}} - Object.keys(key).forEach(function (k) { - builder(k, key[k]) - }) - } else { - // a single key value pair 'x', parse() {} - if (isArray) { - options[type][key] = (options[type][key] || []).concat(value) - } else { - options[type][key] = value - } - } - } - - self.config = function (key, msg, parseFn) { - argsert('[object|string] [string|function] [function]', [key, msg, parseFn], arguments.length) - // allow a config object to be provided directly. - if (typeof key === 'object') { - key = applyExtends(key, cwd) - options.configObjects = (options.configObjects || []).concat(key) - return self - } - - // allow for a custom parsing function. - if (typeof msg === 'function') { - parseFn = msg - msg = null - } - - key = key || 'config' - self.describe(key, msg || usage.deferY18nLookup('Path to JSON config file')) - ;(Array.isArray(key) ? key : [key]).forEach(function (k) { - options.config[k] = parseFn || true - }) - - return self - } - - self.example = function (cmd, description) { - argsert('<string> [string]', [cmd, description], arguments.length) - usage.example(cmd, description) - return self - } - - self.command = function (cmd, description, builder, handler) { - argsert('<string|array|object> [string|boolean] [function|object] [function]', [cmd, description, builder, handler], arguments.length) - command.addHandler(cmd, description, builder, handler) - return self - } - - self.commandDir = function (dir, opts) { - argsert('<string> [object]', [dir, opts], arguments.length) - const req = parentRequire || require - command.addDirectory(dir, self.getContext(), req, require('get-caller-file')(), opts) - return self - } - - // TODO: deprecate self.demand in favor of - // .demandCommand() .demandOption(). - self.demand = self.required = self.require = function (keys, max, msg) { - // you can optionally provide a 'max' key, - // which will raise an exception if too many '_' - // options are provided. - if (Array.isArray(max)) { - max.forEach(function (key) { - self.demandOption(key, msg) - }) - max = Infinity - } else if (typeof max !== 'number') { - msg = max - max = Infinity - } - - if (typeof keys === 'number') { - self.demandCommand(keys, max, msg, msg) - } else if (Array.isArray(keys)) { - keys.forEach(function (key) { - self.demandOption(key, msg) - }) - } else { - if (typeof msg === 'string') { - self.demandOption(keys, msg) - } else if (msg === true || typeof msg === 'undefined') { - self.demandOption(keys) - } - } - - return self - } - - self.demandCommand = function (min, max, minMsg, maxMsg) { - argsert('[number] [number|string] [string|null] [string|null]', [min, max, minMsg, maxMsg], arguments.length) - - if (typeof min === 'undefined') min = 1 - - if (typeof max !== 'number') { - minMsg = max - max = Infinity - } - - self.global('_', false) - - options.demandedCommands._ = { - min: min, - max: max, - minMsg: minMsg, - maxMsg: maxMsg - } - - return self - } - - self.getDemandedOptions = function () { - argsert([], 0) - return options.demandedOptions - } - - self.getDemandedCommands = function () { - argsert([], 0) - return options.demandedCommands - } - - self.implies = function (key, value) { - argsert('<string|object> [string]', [key, value], arguments.length) - validation.implies(key, value) - return self - } - - self.conflicts = function (key1, key2) { - argsert('<string|object> [string]', [key1, key2], arguments.length) - validation.conflicts(key1, key2) - return self - } - - self.usage = function (msg, opts) { - argsert('<string|null|object> [object]', [msg, opts], arguments.length) - - if (!opts && typeof msg === 'object') { - opts = msg - msg = null - } - - usage.usage(msg) - - if (opts) self.options(opts) - - return self - } - - self.epilogue = self.epilog = function (msg) { - argsert('<string>', [msg], arguments.length) - usage.epilog(msg) - return self - } - - self.fail = function (f) { - argsert('<function>', [f], arguments.length) - usage.failFn(f) - return self - } - - self.check = function (f, _global) { - argsert('<function> [boolean]', [f, _global], arguments.length) - validation.check(f, _global !== false) - return self - } - - self.global = function (globals, global) { - argsert('<string|array> [boolean]', [globals, global], arguments.length) - globals = [].concat(globals) - if (global !== false) { - options.local = options.local.filter(function (l) { - return globals.indexOf(l) === -1 - }) - } else { - globals.forEach(function (g) { - if (options.local.indexOf(g) === -1) options.local.push(g) - }) - } - return self - } - - self.pkgConf = function (key, path) { - argsert('<string> [string]', [key, path], arguments.length) - var conf = null - // prefer cwd to require-main-filename in this method - // since we're looking for e.g. "nyc" config in nyc consumer - // rather than "yargs" config in nyc (where nyc is the main filename) - var obj = pkgUp(path || cwd) - - // If an object exists in the key, add it to options.configObjects - if (obj[key] && typeof obj[key] === 'object') { - conf = applyExtends(obj[key], path || cwd) - options.configObjects = (options.configObjects || []).concat(conf) - } - - return self - } - - var pkgs = {} - function pkgUp (path) { - var npath = path || '*' - if (pkgs[npath]) return pkgs[npath] - const readPkgUp = require('read-pkg-up') - - var obj = {} - try { - obj = readPkgUp.sync({ - cwd: path || require('require-main-filename')(parentRequire || require), - normalize: false - }) - } catch (noop) {} - - pkgs[npath] = obj.pkg || {} - return pkgs[npath] - } - - var parseFn = null - var parseContext = null - self.parse = function (args, shortCircuit, _parseFn) { - argsert('<string|array> [function|boolean|object] [function]', [args, shortCircuit, _parseFn], arguments.length) - - // a context object can optionally be provided, this allows - // additional information to be passed to a command handler. - if (typeof shortCircuit === 'object') { - parseContext = shortCircuit - shortCircuit = _parseFn - } - - // by providing a function as a second argument to - // parse you can capture output that would otherwise - // default to printing to stdout/stderr. - if (typeof shortCircuit === 'function') { - parseFn = shortCircuit - shortCircuit = null - } - // completion short-circuits the parsing process, - // skipping validation, etc. - if (!shortCircuit) processArgs = args - - freeze() - if (parseFn) exitProcess = false - - var parsed = self._parseArgs(args, shortCircuit) - if (parseFn) parseFn(exitError, parsed, output) - unfreeze() - - return parsed - } - - self._getParseContext = function () { - return parseContext || {} - } - - self._hasParseCallback = function () { - return !!parseFn - } - - self.option = self.options = function (key, opt) { - argsert('<string|object> [object]', [key, opt], arguments.length) - if (typeof key === 'object') { - Object.keys(key).forEach(function (k) { - self.options(k, key[k]) - }) - } else { - if (typeof opt !== 'object') { - opt = {} - } - - options.key[key] = true // track manually set keys. - - if (opt.alias) self.alias(key, opt.alias) - - var demand = opt.demand || opt.required || opt.require - - // deprecated, use 'demandOption' instead - if (demand) { - self.demand(key, demand) - } - - if (opt.demandOption) { - self.demandOption(key, typeof opt.demandOption === 'string' ? opt.demandOption : undefined) - } - - if ('config' in opt) { - self.config(key, opt.configParser) - } - - if ('conflicts' in opt) { - self.conflicts(key, opt.conflicts) - } - - if ('default' in opt) { - self.default(key, opt.default) - } - - if ('implies' in opt) { - self.implies(key, opt.implies) - } - - if ('nargs' in opt) { - self.nargs(key, opt.nargs) - } - - if ('normalize' in opt) { - self.normalize(key) - } - - if ('choices' in opt) { - self.choices(key, opt.choices) - } - - if ('coerce' in opt) { - self.coerce(key, opt.coerce) - } - - if ('group' in opt) { - self.group(key, opt.group) - } - - if (opt.boolean || opt.type === 'boolean') { - self.boolean(key) - if (opt.alias) self.boolean(opt.alias) - } - - if (opt.array || opt.type === 'array') { - self.array(key) - if (opt.alias) self.array(opt.alias) - } - - if (opt.number || opt.type === 'number') { - self.number(key) - if (opt.alias) self.number(opt.alias) - } - - if (opt.string || opt.type === 'string') { - self.string(key) - if (opt.alias) self.string(opt.alias) - } - - if (opt.count || opt.type === 'count') { - self.count(key) - } - - if (typeof opt.global === 'boolean') { - self.global(key, opt.global) - } - - if (opt.defaultDescription) { - options.defaultDescription[key] = opt.defaultDescription - } - - if (opt.skipValidation) { - self.skipValidation(key) - } - - var desc = opt.describe || opt.description || opt.desc - if (desc) { - self.describe(key, desc) - } - - if (opt.requiresArg) { - self.requiresArg(key) - } - } - - return self - } - self.getOptions = function () { - return options - } - - self.group = function (opts, groupName) { - argsert('<string|array> <string>', [opts, groupName], arguments.length) - var existing = preservedGroups[groupName] || groups[groupName] - if (preservedGroups[groupName]) { - // we now only need to track this group name in groups. - delete preservedGroups[groupName] - } - - var seen = {} - groups[groupName] = (existing || []).concat(opts).filter(function (key) { - if (seen[key]) return false - return (seen[key] = true) - }) - return self - } - self.getGroups = function () { - // combine explicit and preserved groups. explicit groups should be first - return assign(groups, preservedGroups) - } - - // as long as options.envPrefix is not undefined, - // parser will apply env vars matching prefix to argv - self.env = function (prefix) { - argsert('[string|boolean]', [prefix], arguments.length) - if (prefix === false) options.envPrefix = undefined - else options.envPrefix = prefix || '' - return self - } - - self.wrap = function (cols) { - argsert('<number|null>', [cols], arguments.length) - usage.wrap(cols) - return self - } - - var strict = false - self.strict = function (enabled) { - argsert('[boolean]', [enabled], arguments.length) - strict = enabled !== false - return self - } - self.getStrict = function () { - return strict - } - - self.showHelp = function (level) { - argsert('[string|function]', [level], arguments.length) - if (!self.parsed) self._parseArgs(processArgs) // run parser, if it has not already been executed. - usage.showHelp(level) - return self - } - - var versionOpt = null - self.version = function (opt, msg, ver) { - argsert('[string|function] [string|function] [string]', [opt, msg, ver], arguments.length) - if (arguments.length === 0) { - ver = guessVersion() - opt = 'version' - } else if (arguments.length === 1) { - ver = opt - opt = 'version' - } else if (arguments.length === 2) { - ver = msg - msg = null - } - - versionOpt = opt - msg = msg || usage.deferY18nLookup('Show version number') - - usage.version(ver || undefined) - self.boolean(versionOpt) - self.describe(versionOpt, msg) - return self - } - - function guessVersion () { - var obj = pkgUp() - - return obj.version || 'unknown' - } - - var helpOpt = null - var useHelpOptAsCommand = false // a call to .help() will enable this - self.addHelpOpt = self.help = function (opt, msg, addImplicitCmd) { - argsert('[string|boolean] [string|boolean] [boolean]', [opt, msg, addImplicitCmd], arguments.length) - - // argument shuffle - if (arguments.length === 0) { - useHelpOptAsCommand = true - } else if (arguments.length === 1) { - if (typeof opt === 'boolean') { - useHelpOptAsCommand = opt - opt = null - } else { - useHelpOptAsCommand = true - } - } else if (arguments.length === 2) { - if (typeof msg === 'boolean') { - useHelpOptAsCommand = msg - msg = null - } else { - useHelpOptAsCommand = true - } - } else { - useHelpOptAsCommand = Boolean(addImplicitCmd) - } - // use arguments, fallback to defaults for opt and msg - helpOpt = opt || 'help' - self.boolean(helpOpt) - self.describe(helpOpt, msg || usage.deferY18nLookup('Show help')) - return self - } - - self.showHelpOnFail = function (enabled, message) { - argsert('[boolean|string] [string]', [enabled, message], arguments.length) - usage.showHelpOnFail(enabled, message) - return self - } - - var exitProcess = true - self.exitProcess = function (enabled) { - argsert('[boolean]', [enabled], arguments.length) - if (typeof enabled !== 'boolean') { - enabled = true - } - exitProcess = enabled - return self - } - self.getExitProcess = function () { - return exitProcess - } - - var completionCommand = null - self.completion = function (cmd, desc, fn) { - argsert('[string] [string|boolean|function] [function]', [cmd, desc, fn], arguments.length) - - // a function to execute when generating - // completions can be provided as the second - // or third argument to completion. - if (typeof desc === 'function') { - fn = desc - desc = null - } - - // register the completion command. - completionCommand = cmd || 'completion' - if (!desc && desc !== false) { - desc = 'generate bash completion script' - } - self.command(completionCommand, desc) - - // a function can be provided - if (fn) completion.registerFunction(fn) - - return self - } - - self.showCompletionScript = function ($0) { - argsert('[string]', [$0], arguments.length) - $0 = $0 || self.$0 - _logger.log(completion.generateCompletionScript($0)) - return self - } - - self.getCompletion = function (args, done) { - argsert('<array> <function>', [args, done], arguments.length) - completion.getCompletion(args, done) - } - - self.locale = function (locale) { - argsert('[string]', [locale], arguments.length) - if (arguments.length === 0) { - guessLocale() - return y18n.getLocale() - } - detectLocale = false - y18n.setLocale(locale) - return self - } - - self.updateStrings = self.updateLocale = function (obj) { - argsert('<object>', [obj], arguments.length) - detectLocale = false - y18n.updateLocale(obj) - return self - } - - var detectLocale = true - self.detectLocale = function (detect) { - argsert('<boolean>', [detect], arguments.length) - detectLocale = detect - return self - } - self.getDetectLocale = function () { - return detectLocale - } - - var hasOutput = false - var exitError = null - // maybe exit, always capture - // context about why we wanted to exit. - self.exit = function (code, err) { - hasOutput = true - exitError = err - if (exitProcess) process.exit(code) - } - - // we use a custom logger that buffers output, - // so that we can print to non-CLIs, e.g., chat-bots. - var _logger = { - log: function () { - const args = [] - for (var i = 0; i < arguments.length; i++) args.push(arguments[i]) - if (!self._hasParseCallback()) console.log.apply(console, args) - hasOutput = true - if (output.length) output += '\n' - output += args.join(' ') - }, - error: function () { - const args = [] - for (var i = 0; i < arguments.length; i++) args.push(arguments[i]) - if (!self._hasParseCallback()) console.error.apply(console, args) - hasOutput = true - if (output.length) output += '\n' - output += args.join(' ') - } - } - self._getLoggerInstance = function () { - return _logger - } - // has yargs output an error our help - // message in the current execution context. - self._hasOutput = function () { - return hasOutput - } - - self._setHasOutput = function () { - hasOutput = true - } - - var recommendCommands - self.recommendCommands = function (recommend) { - argsert('[boolean]', [recommend], arguments.length) - recommendCommands = typeof recommend === 'boolean' ? recommend : true - return self - } - - self.getUsageInstance = function () { - return usage - } - - self.getValidationInstance = function () { - return validation - } - - self.getCommandInstance = function () { - return command - } - - self.terminalWidth = function () { - argsert([], 0) - return typeof process.stdout.columns !== 'undefined' ? process.stdout.columns : null - } - - Object.defineProperty(self, 'argv', { - get: function () { - return self._parseArgs(processArgs) - }, - enumerable: true - }) - - self._parseArgs = function (args, shortCircuit, _skipValidation, commandIndex) { - var skipValidation = !!_skipValidation - args = args || processArgs - - options.__ = y18n.__ - options.configuration = pkgUp()['yargs'] || {} - const parsed = Parser.detailed(args, options) - var argv = parsed.argv - if (parseContext) argv = assign(argv, parseContext) - var aliases = parsed.aliases - - argv.$0 = self.$0 - self.parsed = parsed - - try { - guessLocale() // guess locale lazily, so that it can be turned off in chain. - - // while building up the argv object, there - // are two passes through the parser. If completion - // is being performed short-circuit on the first pass. - if (shortCircuit) { - return argv - } - - if (argv._.length) { - // check for helpOpt in argv._ before running commands - // assumes helpOpt must be valid if useHelpOptAsCommand is true - if (useHelpOptAsCommand) { - // consider any multi-char helpOpt alias as a valid help command - // unless all helpOpt aliases are single-char - // note that parsed.aliases is a normalized bidirectional map :) - var helpCmds = [helpOpt].concat(aliases[helpOpt] || []) - var multiCharHelpCmds = helpCmds.filter(function (k) { - return k.length > 1 - }) - if (multiCharHelpCmds.length) helpCmds = multiCharHelpCmds - // look for and strip any helpCmds from argv._ - argv._ = argv._.filter(function (cmd) { - if (~helpCmds.indexOf(cmd)) { - argv[helpOpt] = true - return false - } - return true - }) - } - - // if there's a handler associated with a - // command defer processing to it. - var handlerKeys = command.getCommands() - if (handlerKeys.length) { - var firstUnknownCommand - for (var i = (commandIndex || 0), cmd; argv._[i] !== undefined; i++) { - cmd = String(argv._[i]) - if (~handlerKeys.indexOf(cmd) && cmd !== completionCommand) { - setPlaceholderKeys(argv) - // commands are executed using a recursive algorithm that executes - // the deepest command first; we keep track of the position in the - // argv._ array that is currently being executed. - return command.runCommand(cmd, self, parsed, i + 1) - } else if (!firstUnknownCommand && cmd !== completionCommand) { - firstUnknownCommand = cmd - break - } - } - - // run the default command, if defined - if (command.hasDefaultCommand() && !argv[helpOpt]) { - setPlaceholderKeys(argv) - return command.runCommand(null, self, parsed) - } - - // recommend a command if recommendCommands() has - // been enabled, and no commands were found to execute - if (recommendCommands && firstUnknownCommand && !argv[helpOpt]) { - validation.recommendCommands(firstUnknownCommand, handlerKeys) - } - } - - // generate a completion script for adding to ~/.bashrc. - if (completionCommand && ~argv._.indexOf(completionCommand) && !argv[completion.completionKey]) { - if (exitProcess) setBlocking(true) - self.showCompletionScript() - self.exit(0) - } - } else if (command.hasDefaultCommand() && !argv[helpOpt]) { - setPlaceholderKeys(argv) - return command.runCommand(null, self, parsed) - } - - // we must run completions first, a user might - // want to complete the --help or --version option. - if (completion.completionKey in argv) { - if (exitProcess) setBlocking(true) - - // we allow for asynchronous completions, - // e.g., loading in a list of commands from an API. - var completionArgs = args.slice(args.indexOf('--' + completion.completionKey) + 1) - completion.getCompletion(completionArgs, function (completions) { - ;(completions || []).forEach(function (completion) { - _logger.log(completion) - }) - - self.exit(0) - }) - return setPlaceholderKeys(argv) - } - - // Handle 'help' and 'version' options - // if we haven't already output help! - if (!hasOutput) { - Object.keys(argv).forEach(function (key) { - if (key === helpOpt && argv[key]) { - if (exitProcess) setBlocking(true) - - skipValidation = true - self.showHelp('log') - self.exit(0) - } else if (key === versionOpt && argv[key]) { - if (exitProcess) setBlocking(true) - - skipValidation = true - usage.showVersion() - self.exit(0) - } - }) - } - - // Check if any of the options to skip validation were provided - if (!skipValidation && options.skipValidation.length > 0) { - skipValidation = Object.keys(argv).some(function (key) { - return options.skipValidation.indexOf(key) >= 0 && argv[key] === true - }) - } - - // If the help or version options where used and exitProcess is false, - // or if explicitly skipped, we won't run validations. - if (!skipValidation) { - if (parsed.error) throw new YError(parsed.error.message) - - // if we're executed via bash completion, don't - // bother with validation. - if (!argv[completion.completionKey]) { - self._runValidation(argv, aliases, {}, parsed.error) - } - } - } catch (err) { - if (err instanceof YError) usage.fail(err.message, err) - else throw err - } - - return setPlaceholderKeys(argv) - } - - self._runValidation = function (argv, aliases, positionalMap, parseErrors) { - if (parseErrors) throw new YError(parseErrors.message) - validation.nonOptionCount(argv) - validation.missingArgumentValue(argv) - validation.requiredArguments(argv) - if (strict) validation.unknownArguments(argv, aliases, positionalMap) - validation.customChecks(argv, aliases) - validation.limitedChoices(argv) - validation.implications(argv) - validation.conflicting(argv) - } - - function guessLocale () { - if (!detectLocale) return - - try { - const osLocale = require('os-locale') - self.locale(osLocale.sync({ spawn: false })) - } catch (err) { - // if we explode looking up locale just noop - // we'll keep using the default language 'en'. - } - } - - function setPlaceholderKeys (argv) { - Object.keys(options.key).forEach(function (key) { - // don't set placeholder keys for dot - // notation options 'foo.bar'. - if (~key.indexOf('.')) return - if (typeof argv[key] === 'undefined') argv[key] = undefined - }) - return argv - } - - return self -} - -// rebase an absolute path to a relative one with respect to a base directory -// exported for tests -exports.rebase = rebase -function rebase (base, dir) { - return path.relative(base, dir) -} diff --git a/node_modules/webpack/package.json b/node_modules/webpack/package.json index ce2d4ae3f..98def2ac0 100644 --- a/node_modules/webpack/package.json +++ b/node_modules/webpack/package.json @@ -1,77 +1,88 @@ { "name": "webpack", - "version": "3.10.0", + "version": "4.19.1", "author": "Tobias Koppers @sokra", "description": "Packs CommonJs/AMD modules for the browser. Allows to split your codebase into multiple bundles, which can be loaded on demand. Support loaders to preprocess files, i.e. json, jsx, es7, css, less, ... and your custom stuff.", + "license": "MIT", "dependencies": { - "acorn": "^5.0.0", - "acorn-dynamic-import": "^2.0.0", - "ajv": "^5.1.5", - "ajv-keywords": "^2.0.0", - "async": "^2.1.2", - "enhanced-resolve": "^3.4.0", - "escope": "^3.6.0", - "interpret": "^1.0.0", - "json-loader": "^0.5.4", - "json5": "^0.5.1", + "@webassemblyjs/ast": "1.7.6", + "@webassemblyjs/helper-module-context": "1.7.6", + "@webassemblyjs/wasm-edit": "1.7.6", + "@webassemblyjs/wasm-parser": "1.7.6", + "acorn": "^5.6.2", + "acorn-dynamic-import": "^3.0.0", + "ajv": "^6.1.0", + "ajv-keywords": "^3.1.0", + "chrome-trace-event": "^1.0.0", + "enhanced-resolve": "^4.1.0", + "eslint-scope": "^4.0.0", + "json-parse-better-errors": "^1.0.2", "loader-runner": "^2.3.0", "loader-utils": "^1.1.0", "memory-fs": "~0.4.1", + "micromatch": "^3.1.8", "mkdirp": "~0.5.0", + "neo-async": "^2.5.0", "node-libs-browser": "^2.0.0", - "source-map": "^0.5.3", - "supports-color": "^4.2.1", - "tapable": "^0.2.7", - "uglifyjs-webpack-plugin": "^0.4.6", - "watchpack": "^1.4.0", - "webpack-sources": "^1.0.1", - "yargs": "^8.0.2" + "schema-utils": "^0.4.4", + "tapable": "^1.1.0", + "uglifyjs-webpack-plugin": "^1.2.4", + "watchpack": "^1.5.0", + "webpack-sources": "^1.2.0" }, - "license": "MIT", "devDependencies": { - "beautify-lint": "^1.0.3", + "@types/node": "^9.6.4", + "@types/tapable": "^1.0.1", + "@types/webpack-sources": "^0.1.4", "benchmark": "^2.1.1", "bundle-loader": "~0.5.0", "codacy-coverage": "^2.0.1", - "coffee-loader": "~0.7.1", - "coffee-script": "^1.10.0", + "coffee-loader": "^0.9.0", + "coffeescript": "^1.10.0", "coveralls": "^2.11.2", "css-loader": "^0.28.3", "es6-promise-polyfill": "^1.1.1", - "eslint": "^4.3.0", - "eslint-plugin-node": "^5.1.1", + "eslint": "^5.2.0", + "eslint-config-prettier": "^2.9.0", + "eslint-plugin-jest": "^21.18.0", + "eslint-plugin-node": "^7.0.1", + "eslint-plugin-prettier": "^2.6.2", "express": "~4.13.1", - "extract-text-webpack-plugin": "^3.0.0", - "file-loader": "^0.11.2", + "file-loader": "^1.1.6", "glob": "^7.1.2", + "husky": "^1.0.0-rc.6", "i18n-webpack-plugin": "^1.0.0", "istanbul": "^0.4.5", "jade": "^1.11.0", "jade-loader": "~0.8.0", - "js-beautify": "^1.5.10", + "jest": "^23.4.1", + "jest-silent-reporter": "^0.0.5", + "json-loader": "^0.5.7", "less": "^2.5.1", "less-loader": "^4.0.3", + "lint-staged": "^7.2.0", "lodash": "^4.17.4", - "mocha": "^3.2.0", - "mocha-lcov-reporter": "^1.0.0", - "nsp": "^2.6.1", + "prettier": "^1.14.0", + "pug": "^2.0.3", + "pug-loader": "^2.4.0", "raw-loader": "~0.5.0", "react": "^15.2.1", "react-dom": "^15.2.1", "rimraf": "^2.6.2", "script-loader": "~0.7.0", - "should": "^11.1.1", "simple-git": "^1.65.0", - "sinon": "^2.3.2", - "style-loader": "^0.18.1", - "url-loader": "~0.5.0", + "style-loader": "^0.19.1", + "typescript": "^3.0.0-rc", + "url-loader": "^0.6.2", "val-loader": "^1.0.2", "vm-browserify": "~0.0.0", + "wast-loader": "^1.5.5", "webpack-dev-middleware": "^1.9.0", - "worker-loader": "^0.8.0" + "worker-loader": "^1.1.1", + "xxhashjs": "^0.2.1" }, "engines": { - "node": ">=4.3.0 <5.0.0 || >=5.10" + "node": ">=6.11.5" }, "repository": { "type": "git", @@ -87,37 +98,94 @@ "buildin/", "hot/", "web_modules/", - "schemas/" + "schemas/", + "SECURITY.md" ], "scripts": { - "test": "mocha test/*.test.js test/*.unittest.js --max-old-space-size=4096 --harmony --trace-deprecation --check-leaks", - "test:integration": "mocha test/*.test.js --max-old-space-size=4096 --harmony --trace-deprecation --check-leaks", - "test:unit": "mocha test/*.unittest.js --max-old-space-size=4096 --harmony --trace-deprecation --check-leaks", - "travis:integration": "npm run cover:init && npm run cover:integration && npm run cover:report-min", - "travis:unit": "npm run cover:init && npm run cover:unit && npm run cover:report-min", - "travis:lint": "npm run lint-files && npm run nsp", - "travis:benchmark": "npm run benchmark", - "appveyor:integration": "npm run cover:init && npm run cover:integration && npm run cover:report-min", - "appveyor:unit": "npm run cover:init && npm run cover:unit && npm run cover:report-min", - "appveyor:benchmark": "npm run benchmark", - "circleci:test": "node node_modules/mocha/bin/mocha --max-old-space-size=4096 --harmony --trace-deprecation test/*.test.js test/*.unittest.js", - "circleci:lint": "npm run lint-files && npm run nsp", + "setup": "node ./setup/setup.js", + "test": "node --max-old-space-size=4096 --trace-deprecation node_modules/jest-cli/bin/jest", + "test:update-snapshots": "yarn jest -u", + "test:integration": "node --max-old-space-size=4096 --trace-deprecation node_modules/jest-cli/bin/jest --testMatch \"<rootDir>/test/*.test.js\"", + "test:basic": "node --max-old-space-size=4096 --trace-deprecation node_modules/jest-cli/bin/jest --testMatch \"<rootDir>/test/{TestCasesNormal,StatsTestCases,ConfigTestCases}.test.js\"", + "test:unit": "node --max-old-space-size=4096 --trace-deprecation node_modules/jest-cli/bin/jest --testMatch \"<rootDir>/test/*.unittest.js\"", + "travis:integration": "yarn cover:init && yarn cover:integration \"test/(?!TestCases)\" --ci $JEST && mv coverage/coverage-final.json coverage/coverage-final-1.json && yarn cover:integration \"test/TestCasesD\" --ci $JEST && mv coverage/coverage-final.json coverage/coverage-final-2.json && yarn cover:integration \"test/TestCases(?!D)\" --ci $JEST && mv coverage/coverage-final.json coverage/coverage-final-3.json", + "travis:basic": "yarn test:basic --ci $JEST", + "travis:lint-unit": "yarn lint && yarn cover:init && yarn cover:unit --ci $JEST", + "travis:benchmark": "yarn benchmark --ci", + "appveyor:integration": "yarn cover:init && yarn cover:integration \"test/(?!TestCases)\" --ci %JEST% && move coverage\\coverage-final.json coverage\\coverage-final-1.json&& yarn cover:integration \"test/TestCasesD\" --ci %JEST% && move coverage\\coverage-final.json coverage\\coverage-final-2.json && yarn cover:integration \"test/TestCases(?!D)\" --ci %JEST% && move coverage\\coverage-final.json coverage\\coverage-final-3.json", + "appveyor:unit": "yarn cover:init && yarn cover:unit --ci %JEST%", + "appveyor:benchmark": "yarn benchmark --ci", "build:examples": "cd examples && node buildAll.js", - "pretest": "npm run lint-files", - "lint-files": "npm run lint && npm run beautify-lint && npm run schema-lint", - "lint": "eslint lib bin hot buildin \"test/**/webpack.config.js\" \"test/binCases/**/test.js\" \"examples/**/webpack.config.js\"", - "fix": "npm run lint -- --fix", - "beautify-lint": "beautify-lint \"lib/**/*.js\" \"hot/**/*.js\" \"bin/**/*.js\" \"benchmark/*.js\" \"test/*.js\"", - "schema-lint": "mocha test/*.lint.js --opts test/lint-mocha.opts", - "nsp": "nsp check --output summary", - "benchmark": "mocha --max-old-space-size=4096 --harmony --trace-deprecation test/*.benchmark.js -R spec", - "cover": "npm run cover:init && npm run cover:all && npm run cover:report", + "pretest": "yarn lint", + "prelint": "yarn setup", + "lint": "yarn code-lint && yarn schema-lint && yarn type-lint", + "code-lint": "eslint --cache \"{setup,lib,bin,hot,buildin,benchmark,tooling,schemas}/**/*.js\" \"test/*.js\" \"test/{configCases,watchCases,statsCases,hotCases}/**/webpack.config.js\" \"examples/**/webpack.config.js\"", + "type-lint": "tsc --pretty", + "fix": "yarn code-lint --fix", + "pretty": "prettier --loglevel warn --write \"*.{ts,js,json}\" \"{setup,lib,bin,hot,buildin,benchmark,tooling,schemas}/**/*.{js,json}\" \"test/*.js\" \"test/{configCases,watchCases,statsCases,hotCases}/**/webpack.config.js\" \"examples/**/webpack.config.js\"", + "schema-lint": "node --max-old-space-size=4096 node_modules/jest-cli/bin/jest --testMatch \"<rootDir>/test/*.lint.js\" --no-verbose", + "benchmark": "node --max-old-space-size=4096 --trace-deprecation node_modules/jest-cli/bin/jest --testMatch \"<rootDir>/test/*.benchmark.js\" --runInBand", + "cover": "yarn cover:init && yarn cover:all && yarn cover:report", "cover:init": "rimraf coverage", - "cover:all": "node --max-old-space-size=4096 --harmony --trace-deprecation ./node_modules/istanbul/lib/cli.js cover --report none node_modules/mocha/bin/_mocha -- test/*.test.js test/*.unittest.js", - "cover:integration": "node --max-old-space-size=4096 --harmony --trace-deprecation ./node_modules/istanbul/lib/cli.js cover --report none node_modules/mocha/bin/_mocha -- test/*.test.js", - "cover:unit": "node --max-old-space-size=4096 --harmony --trace-deprecation ./node_modules/istanbul/lib/cli.js cover --report none node_modules/mocha/bin/_mocha -- test/*.unittest.js", - "cover:report": "istanbul report", - "cover:report-min": "istanbul report --report lcovonly", - "publish-patch": "npm run lint && npm run beautify-lint && mocha && npm version patch && git push && git push --tags && npm publish" + "cover:all": "node --max-old-space-size=4096 node_modules/jest-cli/bin/jest --coverage", + "cover:integration": "node --max-old-space-size=4096 node_modules/jest-cli/bin/jest --testMatch \"<rootDir>/test/*.test.js\" --coverage", + "cover:unit": "node --max-old-space-size=4096 node_modules/jest-cli/bin/jest --testMatch \"<rootDir>/test/*.unittest.js\" --coverage", + "cover:report": "istanbul report" + }, + "husky": { + "hooks": { + "pre-commit": "lint-staged" + } + }, + "lint-staged": { + "*.js|{lib,setup,bin,hot,buildin,tooling,schemas}/**/*.js|test/*.js|{test,examples}/**/webpack.config.js}": [ + "eslint --cache" + ] + }, + "jest": { + "forceExit": true, + "setupTestFrameworkScriptFile": "<rootDir>/test/setupTestFramework.js", + "testMatch": [ + "<rootDir>/test/*.test.js", + "<rootDir>/test/*.unittest.js" + ], + "watchPathIgnorePatterns": [ + "<rootDir>/.git", + "<rootDir>/node_modules", + "<rootDir>/test/js", + "<rootDir>/test/browsertest/js", + "<rootDir>/test/fixtures/temp-cache-fixture", + "<rootDir>/test/fixtures/temp-", + "<rootDir>/benchmark", + "<rootDir>/examples/*/dist", + "<rootDir>/coverage", + "<rootDir>/.eslintcache" + ], + "modulePathIgnorePatterns": [ + "<rootDir>/.git", + "<rootDir>/node_modules/webpack/node_modules", + "<rootDir>/test/js", + "<rootDir>/test/browsertest/js", + "<rootDir>/test/fixtures/temp-cache-fixture", + "<rootDir>/test/fixtures/temp-", + "<rootDir>/benchmark", + "<rootDir>/examples/*/dist", + "<rootDir>/coverage", + "<rootDir>/.eslintcache" + ], + "transformIgnorePatterns": [ + "<rootDir>" + ], + "coverageDirectory": "<rootDir>/coverage", + "coveragePathIgnorePatterns": [ + "\\.runtime\\.js$", + "<rootDir>/test", + "<rootDir>/schemas", + "<rootDir>/node_modules" + ], + "testEnvironment": "node", + "coverageReporters": [ + "json" + ] } } diff --git a/node_modules/webpack/schemas/ajv.absolutePath.js b/node_modules/webpack/schemas/ajv.absolutePath.js index cb5d10be7..2d7c92fdd 100644 --- a/node_modules/webpack/schemas/ajv.absolutePath.js +++ b/node_modules/webpack/schemas/ajv.absolutePath.js @@ -1,29 +1,55 @@ -"use strict";
-
-const getErrorFor = (shouldBeAbsolute, data, schema) => {
- const message = shouldBeAbsolute ?
- `The provided value ${JSON.stringify(data)} is not an absolute path!`
- : `A relative path is expected. However the provided value ${JSON.stringify(data)} is an absolute path!`;
-
- return {
- keyword: "absolutePath",
- params: { absolutePath: data },
- message: message,
- parentSchema: schema,
- };
-};
-module.exports = (ajv) => ajv.addKeyword("absolutePath", {
- errors: true,
- type: "string",
- compile(expected, schema) {
- function callback(data) {
- const passes = expected === /^(?:[A-Za-z]:\\|\/)/.test(data);
- if(!passes) {
- callback.errors = [getErrorFor(expected, data, schema)];
- }
- return passes;
- }
- callback.errors = [];
- return callback;
- }
-});
+"use strict"; + +const errorMessage = (schema, data, message) => ({ + keyword: "absolutePath", + params: { absolutePath: data }, + message: message, + parentSchema: schema +}); + +const getErrorFor = (shouldBeAbsolute, data, schema) => { + const message = shouldBeAbsolute + ? `The provided value ${JSON.stringify(data)} is not an absolute path!` + : `A relative path is expected. However, the provided value ${JSON.stringify( + data + )} is an absolute path!`; + + return errorMessage(schema, data, message); +}; + +module.exports = ajv => + ajv.addKeyword("absolutePath", { + errors: true, + type: "string", + compile(expected, schema) { + function callback(data) { + let passes = true; + const isExclamationMarkPresent = data.includes("!"); + const isCorrectAbsoluteOrRelativePath = + expected === /^(?:[A-Za-z]:\\|\/)/.test(data); + + if (isExclamationMarkPresent) { + callback.errors = [ + errorMessage( + schema, + data, + `The provided value ${JSON.stringify( + data + )} contans exclamation mark (!) which is not allowed because it's reserved for loader syntax.` + ) + ]; + passes = false; + } + + if (!isCorrectAbsoluteOrRelativePath) { + callback.errors = [getErrorFor(expected, data, schema)]; + passes = false; + } + + return passes; + } + callback.errors = []; + + return callback; + } + }); diff --git a/node_modules/webpack/schemas/webpackOptionsSchema.json b/node_modules/webpack/schemas/webpackOptionsSchema.json deleted file mode 100644 index ee38a2021..000000000 --- a/node_modules/webpack/schemas/webpackOptionsSchema.json +++ /dev/null @@ -1,1499 +0,0 @@ -{
- "additionalProperties": false,
- "definitions": {
- "common.arrayOfStringOrStringArrayValues": {
- "items": {
- "description": "string or array of strings",
- "anyOf": [
- {
- "minLength": 1,
- "type": "string"
- },
- {
- "items": {
- "description": "A non-empty string",
- "minLength": 1,
- "type": "string"
- },
- "type": "array"
- }
- ]
- },
- "type": "array"
- },
- "common.arrayOfStringValues": {
- "items": {
- "description": "A non-empty string",
- "minLength": 1,
- "type": "string"
- },
- "type": "array"
- },
- "common.nonEmptyArrayOfUniqueStringValues": {
- "items": {
- "description": "A non-empty string",
- "minLength": 1,
- "type": "string"
- },
- "minItems": 1,
- "type": "array",
- "uniqueItems": true
- },
- "entry": {
- "oneOf": [
- {
- "minProperties": 1,
- "additionalProperties": {
- "description": "An entry point with name",
- "oneOf": [
- {
- "description": "The string is resolved to a module which is loaded upon startup.",
- "minLength": 1,
- "type": "string"
- },
- {
- "description": "All modules are loaded upon startup. The last one is exported.",
- "anyOf": [
- {
- "$ref": "#/definitions/common.nonEmptyArrayOfUniqueStringValues"
- }
- ]
- }
- ]
- },
- "description": "Multiple entry bundles are created. The key is the chunk name. The value can be a string or an array.",
- "type": "object"
- },
- {
- "description": "An entry point without name. The string is resolved to a module which is loaded upon startup.",
- "minLength": 1,
- "type": "string"
- },
- {
- "description": "An entry point without name. All modules are loaded upon startup. The last one is exported.",
- "anyOf": [
- {
- "$ref": "#/definitions/common.nonEmptyArrayOfUniqueStringValues"
- }
- ]
- },
- {
- "description": "A Function returning an entry object, an entry string, an entry array or a promise to these things.",
- "instanceof": "Function"
- }
- ]
- },
- "externals": {
- "anyOf": [
- {
- "description": "An exact matched dependency becomes external. The same string is used as external dependency.",
- "type": "string"
- },
- {
- "additionalProperties": {
- "description": "The dependency used for the external",
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "object"
- },
- {
- "type": "boolean"
- }
- ]
- },
- "description": "If an dependency matches exactly a property of the object, the property value is used as dependency.",
- "type": "object"
- },
- {
- "description": "`function(context, request, callback(err, result))` The function is called on each dependency.",
- "instanceof": "Function"
- },
- {
- "description": "Every matched dependency becomes external.",
- "instanceof": "RegExp"
- },
- {
- "items": {
- "description": "External configuration",
- "anyOf": [
- {
- "$ref": "#/definitions/externals"
- }
- ]
- },
- "type": "array"
- }
- ]
- },
- "module": {
- "additionalProperties": false,
- "properties": {
- "exprContextCritical": {
- "description": "Enable warnings for full dynamic dependencies",
- "type": "boolean"
- },
- "exprContextRecursive": {
- "description": "Enable recursive directory lookup for full dynamic dependencies",
- "type": "boolean"
- },
- "exprContextRegExp": {
- "description": "Sets the default regular expression for full dynamic dependencies",
- "anyOf": [
- {
- "type": "boolean"
- },
- {
- "instanceof": "RegExp"
- }
- ]
- },
- "exprContextRequest": {
- "description": "Set the default request for full dynamic dependencies",
- "type": "string"
- },
- "loaders": {
- "description": "An array of automatically applied loaders.",
- "anyOf": [
- {
- "$ref": "#/definitions/ruleSet-rules"
- }
- ]
- },
- "noParse": {
- "description": "Don't parse files matching. It's matched against the full resolved request.",
- "anyOf": [
- {
- "items": {
- "description": "A regular expression, when matched the module is not parsed",
- "instanceof": "RegExp"
- },
- "minItems": 1,
- "type": "array"
- },
- {
- "instanceof": "RegExp"
- },
- {
- "instanceof": "Function"
- },
- {
- "items": {
- "description": "An absolute path, when the module starts with this path it is not parsed",
- "type": "string",
- "absolutePath": true
- },
- "minItems": 1,
- "type": "array"
- },
- {
- "type": "string",
- "absolutePath": true
- }
- ]
- },
- "rules": {
- "allOf": [
- {
- "$ref": "#/definitions/ruleSet-rules"
- }
- ],
- "description": "An array of rules applied for modules."
- },
- "unknownContextCritical": {
- "description": "Enable warnings when using the require function in a not statically analyse-able way",
- "type": "boolean"
- },
- "unknownContextRecursive": {
- "description": "Enable recursive directory lookup when using the require function in a not statically analyse-able way",
- "type": "boolean"
- },
- "unknownContextRegExp": {
- "description": "Sets the regular expression when using the require function in a not statically analyse-able way",
- "anyOf": [
- {
- "type": "boolean"
- },
- {
- "instanceof": "RegExp"
- }
- ]
- },
- "unknownContextRequest": {
- "description": "Sets the request when using the require function in a not statically analyse-able way",
- "type": "string"
- },
- "unsafeCache": {
- "description": "Cache the resolving of module requests",
- "anyOf": [
- {
- "type": "boolean"
- },
- {
- "instanceof": "Function"
- }
- ]
- },
- "wrappedContextCritical": {
- "description": "Enable warnings for partial dynamic dependencies",
- "type": "boolean"
- },
- "wrappedContextRecursive": {
- "description": "Enable recursive directory lookup for partial dynamic dependencies",
- "type": "boolean"
- },
- "wrappedContextRegExp": {
- "description": "Set the inner regular expression for partial dynamic dependencies",
- "instanceof": "RegExp"
- },
- "strictExportPresence": {
- "description": "Emit errors instead of warnings when imported names don't exist in imported module",
- "type": "boolean"
- },
- "strictThisContextOnImports": {
- "description": "Handle the this context correctly according to the spec for namespace objects",
- "type": "boolean"
- }
- },
- "type": "object"
- },
- "output": {
- "additionalProperties": false,
- "properties": {
- "auxiliaryComment": {
- "description": "Add a comment in the UMD wrapper.",
- "anyOf": [
- {
- "description": "Append the same comment above each import style.",
- "type": "string"
- },
- {
- "additionalProperties": false,
- "description": "Set explicit comments for `commonjs`, `commonjs2`, `amd`, and `root`.",
- "properties": {
- "amd": {
- "description": "Set comment for `amd` section in UMD",
- "type": "string"
- },
- "commonjs": {
- "description": "Set comment for `commonjs` (exports) section in UMD",
- "type": "string"
- },
- "commonjs2": {
- "description": "Set comment for `commonjs2` (module.exports) section in UMD",
- "type": "string"
- },
- "root": {
- "description": "Set comment for `root` (global variable) section in UMD",
- "type": "string"
- }
- },
- "type": "object"
- }
- ]
- },
- "chunkFilename": {
- "description": "The filename of non-entry chunks as relative path inside the `output.path` directory.",
- "type": "string",
- "absolutePath": false
- },
- "crossOriginLoading": {
- "description": "This option enables cross-origin loading of chunks.",
- "enum": [
- false,
- "anonymous",
- "use-credentials"
- ]
- },
- "chunkLoadTimeout": {
- "description": "Number of milliseconds before chunk request expires",
- "type": "number"
- },
- "devtoolFallbackModuleFilenameTemplate": {
- "description": "Similar to `output.devtoolModuleFilenameTemplate`, but used in the case of duplicate module identifiers.",
- "anyOf": [
- {
- "type": "string"
- },
- {
- "instanceof": "Function"
- }
- ]
- },
- "devtoolLineToLine": {
- "description": "Enable line to line mapped mode for all/specified modules. Line to line mapped mode uses a simple SourceMap where each line of the generated source is mapped to the same line of the original source. It’s a performance optimization. Only use it if your performance need to be better and you are sure that input lines match which generated lines.",
- "anyOf": [
- {
- "description": "`true` enables it for all modules (not recommended)",
- "type": "boolean"
- },
- {
- "description": "An object similar to `module.loaders` enables it for specific files.",
- "type": "object"
- }
- ]
- },
- "devtoolModuleFilenameTemplate": {
- "description": "Filename template string of function for the sources array in a generated SourceMap.",
- "anyOf": [
- {
- "type": "string"
- },
- {
- "instanceof": "Function"
- }
- ]
- },
- "filename": {
- "description": "Specifies the name of each output file on disk. You must **not** specify an absolute path here! The `output.path` option determines the location on disk the files are written to, filename is used solely for naming the individual files.",
- "type": "string",
- "absolutePath": false
- },
- "hashDigest": {
- "description": "Digest type used for the hash",
- "enum": [
- "latin1",
- "hex",
- "base64"
- ]
- },
- "hashDigestLength": {
- "description": "Number of chars which are used for the hash",
- "minimum": 1,
- "type": "number"
- },
- "hashFunction": {
- "description": "Algorithm used for generation the hash (see node.js crypto package)",
- "minLength": 1,
- "type": "string"
- },
- "hashSalt": {
- "description": "Any string which is added to the hash to salt it",
- "minLength": 1,
- "type": "string"
- },
- "hotUpdateChunkFilename": {
- "description": "The filename of the Hot Update Chunks. They are inside the output.path directory.",
- "type": "string",
- "absolutePath": false
- },
- "hotUpdateFunction": {
- "description": "The JSONP function used by webpack for async loading of hot update chunks.",
- "type": "string"
- },
- "hotUpdateMainFilename": {
- "description": "The filename of the Hot Update Main File. It is inside the `output.path` directory.",
- "type": "string",
- "absolutePath": false
- },
- "jsonpFunction": {
- "description": "The JSONP function used by webpack for async loading of chunks.",
- "type": "string"
- },
- "library": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "items": {
- "description": "A part of the library name",
- "type": "string"
- },
- "type": "array"
- },
- {
- "type": "object",
- "additionalProperties": false,
- "properties": {
- "root": {
- "description": "Name of the property exposed globally by a UMD library",
- "type": "string"
- },
- "amd": {
- "description": "Name of the exposed AMD library in the UMD",
- "type": "string"
- },
- "commonjs": {
- "description": "Name of the exposed commonjs export in the UMD",
- "type": "string"
- }
- }
- }
- ],
- "description": "If set, export the bundle as library. `output.library` is the name."
- },
- "libraryTarget": {
- "description": "Type of library",
- "enum": [
- "var",
- "assign",
- "this",
- "window",
- "global",
- "commonjs",
- "commonjs2",
- "commonjs-module",
- "amd",
- "umd",
- "umd2",
- "jsonp"
- ]
- },
- "libraryExport": {
- "description": "Specify which export should be exposed as library",
- "anyOf": [
- {
- "type": "string"
- },
- {
- "$ref": "#/definitions/common.arrayOfStringValues"
- }
- ]
- },
- "path": {
- "description": "The output directory as **absolute path** (required).",
- "type": "string",
- "absolutePath": true
- },
- "pathinfo": {
- "description": "Include comments with information about the modules.",
- "type": "boolean"
- },
- "publicPath": {
- "description": "The `publicPath` specifies the public URL address of the output files when referenced in a browser.",
- "type": "string"
- },
- "sourceMapFilename": {
- "description": "The filename of the SourceMaps for the JavaScript files. They are inside the `output.path` directory.",
- "type": "string",
- "absolutePath": false
- },
- "sourcePrefix": {
- "description": "Prefixes every line of the source in the bundle with this string.",
- "type": "string"
- },
- "strictModuleExceptionHandling": {
- "description": "Handles exceptions in module loading correctly at a performance cost.",
- "type": "boolean"
- },
- "umdNamedDefine": {
- "description": "If `output.libraryTarget` is set to umd and `output.library` is set, setting this to true will name the AMD module.",
- "type": "boolean"
- }
- },
- "type": "object"
- },
- "resolve": {
- "additionalProperties": false,
- "properties": {
- "alias": {
- "description": "Redirect module requests",
- "anyOf": [
- {
- "additionalProperties": {
- "description": "New request",
- "type": "string"
- },
- "type": "object"
- },
- {
- "items": {
- "description": "Alias configuration",
- "additionalProperties": false,
- "properties": {
- "alias": {
- "description": "New request",
- "type": "string"
- },
- "name": {
- "description": "Request to be redirected",
- "type": "string"
- },
- "onlyModule": {
- "description": "Redirect only exact matching request",
- "type": "boolean"
- }
- },
- "type": "object"
- },
- "type": "array"
- }
- ]
- },
- "aliasFields": {
- "description": "Fields in the description file (package.json) which are used to redirect requests inside the module",
- "anyOf": [
- {
- "$ref": "#/definitions/common.arrayOfStringOrStringArrayValues"
- }
- ]
- },
- "cachePredicate": {
- "description": "Predicate function to decide which requests should be cached",
- "instanceof": "Function"
- },
- "cacheWithContext": {
- "description": "Include the context information in the cache identifier when caching",
- "type": "boolean"
- },
- "descriptionFiles": {
- "description": "Filenames used to find a description file",
- "anyOf": [
- {
- "$ref": "#/definitions/common.arrayOfStringValues"
- }
- ]
- },
- "enforceExtension": {
- "description": "Enforce using one of the extensions from the extensions option",
- "type": "boolean"
- },
- "enforceModuleExtension": {
- "description": "Enforce using one of the module extensions from the moduleExtensions option",
- "type": "boolean"
- },
- "extensions": {
- "description": "Extensions added to the request when trying to find the file",
- "anyOf": [
- {
- "$ref": "#/definitions/common.arrayOfStringValues"
- }
- ]
- },
- "fileSystem": {
- "description": "Filesystem for the resolver"
- },
- "mainFields": {
- "description": "Field names from the description file (package.json) which are used to find the default entry point",
- "anyOf": [
- {
- "$ref": "#/definitions/common.arrayOfStringOrStringArrayValues"
- }
- ]
- },
- "mainFiles": {
- "description": "Filenames used to find the default entry point if there is no description file or main field",
- "anyOf": [
- {
- "$ref": "#/definitions/common.arrayOfStringValues"
- }
- ]
- },
- "moduleExtensions": {
- "description": "Extenstions added to the module request when trying to find the module",
- "anyOf": [
- {
- "$ref": "#/definitions/common.arrayOfStringValues"
- }
- ]
- },
- "modules": {
- "description": "Folder names or directory paths where to find modules",
- "anyOf": [
- {
- "$ref": "#/definitions/common.arrayOfStringValues"
- }
- ]
- },
- "plugins": {
- "description": "Plugins for the resolver",
- "type": "array"
- },
- "resolver": {
- "description": "Custom resolver"
- },
- "symlinks": {
- "description": "Enable resolving symlinks to the original location",
- "type": "boolean"
- },
- "unsafeCache": {
- "description": "Enable caching of successfully resolved requests",
- "anyOf": [
- {
- "type": "boolean"
- },
- {
- "additionalProperties": true,
- "type": "object"
- }
- ]
- },
- "useSyncFileSystemCalls": {
- "description": "Use synchronous filesystem calls for the resolver",
- "type": "boolean"
- }
- },
- "type": "object"
- },
- "ruleSet-condition": {
- "anyOf": [
- {
- "instanceof": "RegExp"
- },
- {
- "minLength": 1,
- "type": "string"
- },
- {
- "instanceof": "Function"
- },
- {
- "$ref": "#/definitions/ruleSet-conditions"
- },
- {
- "additionalProperties": false,
- "properties": {
- "and": {
- "description": "Logical AND",
- "anyOf": [
- {
- "$ref": "#/definitions/ruleSet-conditions"
- }
- ]
- },
- "exclude": {
- "description": "Exclude all modules matching any of these conditions",
- "anyOf": [
- {
- "$ref": "#/definitions/ruleSet-condition"
- }
- ]
- },
- "include": {
- "description": "Exclude all modules matching not any of these conditions",
- "anyOf": [
- {
- "$ref": "#/definitions/ruleSet-condition"
- }
- ]
- },
- "not": {
- "description": "Logical NOT",
- "anyOf": [
- {
- "$ref": "#/definitions/ruleSet-conditions"
- }
- ]
- },
- "or": {
- "description": "Logical OR",
- "anyOf": [
- {
- "$ref": "#/definitions/ruleSet-conditions"
- }
- ]
- },
- "test": {
- "description": "Exclude all modules matching any of these conditions",
- "anyOf": [
- {
- "$ref": "#/definitions/ruleSet-condition"
- }
- ]
- }
- },
- "type": "object"
- }
- ]
- },
- "ruleSet-conditions": {
- "items": {
- "description": "A rule condition",
- "anyOf": [
- {
- "$ref": "#/definitions/ruleSet-condition"
- }
- ]
- },
- "type": "array"
- },
- "ruleSet-loader": {
- "minLength": 1,
- "type": "string"
- },
- "ruleSet-query": {
- "anyOf": [
- {
- "type": "object"
- },
- {
- "type": "string"
- }
- ]
- },
- "ruleSet-rule": {
- "additionalProperties": false,
- "properties": {
- "enforce": {
- "description": "Enforce this rule as pre or post step",
- "enum": [
- "pre",
- "post"
- ]
- },
- "exclude": {
- "description": "Shortcut for resource.exclude",
- "allOf": [
- {
- "$ref": "#/definitions/ruleSet-condition"
- },
- {
- "absolutePath": true
- }
- ]
- },
- "include": {
- "description": "Shortcut for resource.include",
- "allOf": [
- {
- "$ref": "#/definitions/ruleSet-condition"
- },
- {
- "absolutePath": true
- }
- ]
- },
- "issuer": {
- "description": "Match the issuer of the module (The module pointing to this module)",
- "allOf": [
- {
- "$ref": "#/definitions/ruleSet-condition"
- },
- {
- "absolutePath": true
- }
- ]
- },
- "loader": {
- "description": "Shortcut for use.loader",
- "anyOf": [
- {
- "$ref": "#/definitions/ruleSet-loader"
- },
- {
- "$ref": "#/definitions/ruleSet-use"
- }
- ]
- },
- "loaders": {
- "description": "Shortcut for use.loader",
- "anyOf": [
- {
- "$ref": "#/definitions/ruleSet-use"
- }
- ]
- },
- "oneOf": {
- "description": "Only execute the first matching rule in this array",
- "anyOf": [
- {
- "$ref": "#/definitions/ruleSet-rules"
- }
- ]
- },
- "options": {
- "description": "Shortcut for use.options",
- "anyOf": [
- {
- "$ref": "#/definitions/ruleSet-query"
- }
- ]
- },
- "parser": {
- "description": "Options for parsing",
- "additionalProperties": true,
- "type": "object"
- },
- "query": {
- "description": "Shortcut for use.query",
- "anyOf": [
- {
- "$ref": "#/definitions/ruleSet-query"
- }
- ]
- },
- "resource": {
- "description": "Match the resource path of the module",
- "allOf": [
- {
- "$ref": "#/definitions/ruleSet-condition"
- },
- {
- "absolutePath": true
- }
- ]
- },
- "resourceQuery": {
- "description": "Match the resource query of the module",
- "anyOf": [
- {
- "$ref": "#/definitions/ruleSet-condition"
- }
- ]
- },
- "compiler": {
- "description": "Match the child compiler name",
- "anyOf": [
- {
- "$ref": "#/definitions/ruleSet-condition"
- }
- ]
- },
- "rules": {
- "description": "Match and execute these rules when this rule is matched",
- "anyOf": [
- {
- "$ref": "#/definitions/ruleSet-rules"
- }
- ]
- },
- "test": {
- "description": "Shortcut for resource.test",
- "allOf": [
- {
- "$ref": "#/definitions/ruleSet-condition"
- },
- {
- "absolutePath": true
- }
- ]
- },
- "use": {
- "description": "Modifiers applied to the module when rule is matched",
- "anyOf": [
- {
- "$ref": "#/definitions/ruleSet-use"
- }
- ]
- }
- },
- "type": "object"
- },
- "ruleSet-rules": {
- "items": {
- "description": "A rule",
- "anyOf": [
- {
- "$ref": "#/definitions/ruleSet-rule"
- }
- ]
- },
- "type": "array"
- },
- "ruleSet-use": {
- "anyOf": [
- {
- "$ref": "#/definitions/ruleSet-use-item"
- },
- {
- "instanceof": "Function"
- },
- {
- "items": {
- "description": "An use item",
- "anyOf": [
- {
- "$ref": "#/definitions/ruleSet-use-item"
- }
- ]
- },
- "type": "array"
- }
- ]
- },
- "ruleSet-use-item": {
- "anyOf": [
- {
- "$ref": "#/definitions/ruleSet-loader"
- },
- {
- "instanceof": "Function"
- },
- {
- "additionalProperties": false,
- "properties": {
- "loader": {
- "description": "Loader name",
- "anyOf": [
- {
- "$ref": "#/definitions/ruleSet-loader"
- }
- ]
- },
- "options": {
- "description": "Loader options",
- "anyOf": [
- {
- "$ref": "#/definitions/ruleSet-query"
- }
- ]
- },
- "query": {
- "description": "Loader query",
- "anyOf": [
- {
- "$ref": "#/definitions/ruleSet-query"
- }
- ]
- }
- },
- "type": "object"
- }
- ]
- },
- "filter-item-types": {
- "anyOf": [
- {
- "instanceof": "RegExp"
- },
- {
- "type": "string"
- },
- {
- "instanceof": "Function"
- }
- ]
- },
- "filter-types": {
- "anyOf": [
- {
- "$ref": "#/definitions/filter-item-types"
- },
- {
- "type": "array",
- "items": {
- "description": "Rule to filter",
- "anyOf": [
- {
- "$ref": "#/definitions/filter-item-types"
- }
- ]
- }
- }
- ]
- }
- },
- "properties": {
- "amd": {
- "description": "Set the value of `require.amd` and `define.amd`."
- },
- "bail": {
- "description": "Report the first error as a hard error instead of tolerating it.",
- "type": "boolean"
- },
- "cache": {
- "description": "Cache generated modules and chunks to improve performance for multiple incremental builds.",
- "anyOf": [
- {
- "description": "You can pass `false` to disable it.",
- "type": "boolean"
- },
- {
- "description": "You can pass an object to enable it and let webpack use the passed object as cache. This way you can share the cache object between multiple compiler calls.",
- "type": "object"
- }
- ]
- },
- "context": {
- "description": "The base directory (absolute path!) for resolving the `entry` option. If `output.pathinfo` is set, the included pathinfo is shortened to this directory.",
- "type": "string",
- "absolutePath": true
- },
- "dependencies": {
- "description": "References to other configurations to depend on.",
- "items": {
- "description": "References to another configuration to depend on.",
- "type": "string"
- },
- "type": "array"
- },
- "devServer": {
- "description": "Options for the webpack-dev-server",
- "type": "object"
- },
- "devtool": {
- "description": "A developer tool to enhance debugging.",
- "anyOf": [
- {
- "type": "string"
- },
- {
- "enum": [
- false
- ]
- }
- ]
- },
- "entry": {
- "description": "The entry point(s) of the compilation.",
- "anyOf": [
- {
- "$ref": "#/definitions/entry"
- }
- ]
- },
- "externals": {
- "description": "Specify dependencies that shouldn't be resolved by webpack, but should become dependencies of the resulting bundle. The kind of the dependency depends on `output.libraryTarget`.",
- "anyOf": [
- {
- "$ref": "#/definitions/externals"
- }
- ]
- },
- "loader": {
- "description": "Custom values available in the loader context.",
- "type": "object"
- },
- "module": {
- "description": "Options affecting the normal modules (`NormalModuleFactory`).",
- "anyOf": [
- {
- "$ref": "#/definitions/module"
- }
- ]
- },
- "name": {
- "description": "Name of the configuration. Used when loading multiple configurations.",
- "type": "string"
- },
- "node": {
- "description": "Include polyfills or mocks for various node stuff.",
- "anyOf": [
- {
- "enum": [
- false
- ]
- },
- {
- "additionalProperties": {
- "description": "Include a polyfill for the node.js module",
- "enum": [
- false,
- true,
- "mock",
- "empty"
- ]
- },
- "properties": {
- "Buffer": {
- "description": "Include a polyfill for the 'Buffer' variable",
- "enum": [
- false,
- true,
- "mock"
- ]
- },
- "__dirname": {
- "description": "Include a polyfill for the '__dirname' variable",
- "enum": [
- false,
- true,
- "mock"
- ]
- },
- "__filename": {
- "description": "Include a polyfill for the '__filename' variable",
- "enum": [
- false,
- true,
- "mock"
- ]
- },
- "console": {
- "description": "Include a polyfill for the 'console' variable",
- "enum": [
- false,
- true,
- "mock"
- ]
- },
- "global": {
- "description": "Include a polyfill for the 'global' variable",
- "type": "boolean"
- },
- "process": {
- "description": "Include a polyfill for the 'process' variable",
- "enum": [
- false,
- true,
- "mock"
- ]
- }
- },
- "type": "object"
- }
- ]
- },
- "output": {
- "description": "Options affecting the output of the compilation. `output` options tell webpack how to write the compiled files to disk.",
- "anyOf": [
- {
- "$ref": "#/definitions/output"
- }
- ]
- },
- "parallelism": {
- "description": "The number of parallel processed modules in the compilation.",
- "minimum": 1,
- "type": "number"
- },
- "performance": {
- "description": "Configuration for web performance recommendations.",
- "anyOf": [
- {
- "enum": [
- false
- ]
- },
- {
- "additionalProperties": false,
- "properties": {
- "assetFilter": {
- "description": "Filter function to select assets that are checked",
- "instanceof": "Function"
- },
- "hints": {
- "description": "Sets the format of the hints: warnings, errors or nothing at all",
- "enum": [
- false,
- "warning",
- "error"
- ]
- },
- "maxEntrypointSize": {
- "description": "Total size of an entry point (in bytes)",
- "type": "number"
- },
- "maxAssetSize": {
- "description": "Filesize limit (in bytes) when exceeded, that webpack will provide performance hints",
- "type": "number"
- }
- },
- "type": "object"
- }
- ]
- },
- "plugins": {
- "description": "Add additional plugins to the compiler.",
- "type": "array"
- },
- "profile": {
- "description": "Capture timing information for each module.",
- "type": "boolean"
- },
- "recordsInputPath": {
- "description": "Store compiler state to a json file.",
- "type": "string",
- "absolutePath": true
- },
- "recordsOutputPath": {
- "description": "Load compiler state from a json file.",
- "type": "string",
- "absolutePath": true
- },
- "recordsPath": {
- "description": "Store/Load compiler state from/to a json file. This will result in persistent ids of modules and chunks. An absolute path is expected. `recordsPath` is used for `recordsInputPath` and `recordsOutputPath` if they left undefined.",
- "type": "string",
- "absolutePath": true
- },
- "resolve": {
- "description": "Options for the resolver",
- "anyOf": [
- {
- "$ref": "#/definitions/resolve"
- }
- ]
- },
- "resolveLoader": {
- "description": "Options for the resolver when resolving loaders",
- "anyOf": [
- {
- "$ref": "#/definitions/resolve"
- }
- ]
- },
- "stats": {
- "description": "Used by the webpack CLI program to pass stats options.",
- "anyOf": [
- {
- "type": "object",
- "additionalProperties": false,
- "properties": {
- "all": {
- "type": "boolean",
- "description": "fallback value for stats options when an option is not defined (has precedence over local webpack defaults)"
- },
- "context": {
- "type": "string",
- "description": "context directory for request shortening",
- "absolutePath": true
- },
- "hash": {
- "type": "boolean",
- "description": "add the hash of the compilation"
- },
- "version": {
- "type": "boolean",
- "description": "add webpack version information"
- },
- "timings": {
- "type": "boolean",
- "description": "add timing information"
- },
- "performance": {
- "type": "boolean",
- "description": "add performance hint flags"
- },
- "depth": {
- "type": "boolean",
- "description": "add module depth in module graph"
- },
- "assets": {
- "type": "boolean",
- "description": "add assets information"
- },
- "env": {
- "type": "boolean",
- "description": "add --env information"
- },
- "colors": {
- "description": "Enables/Disables colorful output",
- "oneOf": [
- {
- "type": "boolean",
- "description": "`webpack --colors` equivalent"
- },
- {
- "type": "object",
- "additionalProperties": false,
- "properties": {
- "bold": {
- "description": "Custom color for bold text",
- "type": "string"
- },
- "red": {
- "description": "Custom color for red text",
- "type": "string"
- },
- "green": {
- "description": "Custom color for green text",
- "type": "string"
- },
- "cyan": {
- "description": "Custom color for cyan text",
- "type": "string"
- },
- "magenta": {
- "description": "Custom color for magenta text",
- "type": "string"
- },
- "yellow": {
- "description": "Custom color for yellow text",
- "type": "string"
- }
- }
- }
- ]
- },
- "maxModules": {
- "type": "number",
- "description": "Set the maximum number of modules to be shown"
- },
- "chunks": {
- "type": "boolean",
- "description": "add chunk information"
- },
- "chunkModules": {
- "type": "boolean",
- "description": "add built modules information to chunk information"
- },
- "modules": {
- "type": "boolean",
- "description": "add built modules information"
- },
- "children": {
- "type": "boolean",
- "description": "add children information"
- },
- "cached": {
- "type": "boolean",
- "description": "add also information about cached (not built) modules"
- },
- "cachedAssets": {
- "type": "boolean",
- "description": "Show cached assets (setting this to `false` only shows emitted files)"
- },
- "reasons": {
- "type": "boolean",
- "description": "add information about the reasons why modules are included"
- },
- "source": {
- "type": "boolean",
- "description": "add the source code of modules"
- },
- "warnings": {
- "type": "boolean",
- "description": "add warnings"
- },
- "errors": {
- "type": "boolean",
- "description": "add errors"
- },
- "warningsFilter": {
- "description": "Suppress warnings that match the specified filters. Filters can be Strings, RegExps or Functions",
- "anyOf": [
- {
- "$ref": "#/definitions/filter-types"
- }
- ]
- },
- "excludeAssets": {
- "description": "Suppress assets that match the specified filters. Filters can be Strings, RegExps or Functions",
- "anyOf": [
- {
- "$ref": "#/definitions/filter-types"
- }
- ]
- },
- "excludeModules": {
- "description": "Suppress modules that match the specified filters. Filters can be Strings, RegExps or Functions",
- "anyOf": [
- {
- "$ref": "#/definitions/filter-types"
- }
- ]
- },
- "exclude": {
- "description": "Please use excludeModules instead.",
- "anyOf": [
- {
- "$ref": "#/definitions/filter-types"
- }
- ]
- },
- "entrypoints": {
- "type": "boolean",
- "description": "Display the entry points with the corresponding bundles"
- },
- "errorDetails": {
- "type": "boolean",
- "description": "add details to errors (like resolving log)"
- },
- "chunkOrigins": {
- "type": "boolean",
- "description": "add the origins of chunks and chunk merging info"
- },
- "modulesSort": {
- "type": "string",
- "description": "sort the modules by that field"
- },
- "moduleTrace": {
- "type": "boolean",
- "description": "add dependencies and origin of warnings/errors"
- },
- "chunksSort": {
- "type": "string",
- "description": "sort the chunks by that field"
- },
- "assetsSort": {
- "type": "string",
- "description": "sort the assets by that field"
- },
- "publicPath": {
- "type": "boolean",
- "description": "Add public path information"
- },
- "providedExports": {
- "type": "boolean",
- "description": "show exports provided by modules"
- },
- "usedExports": {
- "type": "boolean",
- "description": "show exports used by modules"
- },
- "optimizationBailout": {
- "type": "boolean",
- "description": "show reasons why optimization bailed out for modules"
- }
- }
- },
- {
- "type": "boolean"
- },
- {
- "enum": [
- "none",
- "errors-only",
- "minimal",
- "normal",
- "detailed",
- "verbose"
- ]
- }
- ]
- },
- "target": {
- "description": "Environment to build for",
- "anyOf": [
- {
- "enum": [
- "web",
- "webworker",
- "node",
- "async-node",
- "node-webkit",
- "atom",
- "electron",
- "electron-main",
- "electron-renderer"
- ]
- },
- {
- "instanceof": "Function"
- }
- ]
- },
- "watch": {
- "description": "Enter watch mode, which rebuilds on file change.",
- "type": "boolean"
- },
- "watchOptions": {
- "description": "Options for the watcher",
- "additionalProperties": false,
- "properties": {
- "aggregateTimeout": {
- "description": "Delay the rebuilt after the first change. Value is a time in ms.",
- "type": "number"
- },
- "ignored": {
- "description": "Ignore some files from watching"
- },
- "stdin": {
- "description": "Stop watching when stdin stream has ended",
- "type": "boolean"
- },
- "poll": {
- "description": "Enable polling mode for watching",
- "anyOf": [
- {
- "description": "`true`: use polling.",
- "type": "boolean"
- },
- {
- "description": "`number`: use polling with specified interval.",
- "type": "number"
- }
- ]
- }
- },
- "type": "object"
- }
- },
- "required": [
- "entry"
- ],
- "type": "object"
-}
|