code:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

const createMappingsSerializer = require("./createMappingsSerializer");
const streamChunks = require("./streamChunks");

const streamAndGetSourceAndMap = (
	inputSource,
	options,
	onChunk,
	onSource,
	onName
) => {
	let code = "";
	let mappings = "";
	let sources = [];
	let sourcesContent = [];
	let names = [];
	const addMapping = createMappingsSerializer(
		Object.assign({}, options, { columns: true })
	);
	const finalSource = !!(options && options.finalSource);
	const { generatedLine, generatedColumn, source } = streamChunks(
		inputSource,
		options,
		(
			chunk,
			generatedLine,
			generatedColumn,
			sourceIndex,
			originalLine,
			originalColumn,
			nameIndex
		) => {
			if (chunk !== undefined) code += chunk;
			mappings += addMapping(
				generatedLine,
				generatedColumn,
				sourceIndex,
				originalLine,
				originalColumn,
				nameIndex
			);
			return onChunk(
				finalSource ? undefined : chunk,
				generatedLine,
				generatedColumn,
				sourceIndex,
				originalLine,
				originalColumn,
				nameIndex
			);
		},
		(sourceIndex, source, sourceContent) => {
			while (sources.length < sourceIndex) {
				sources.push(null);
			}
			sources[sourceIndex] = source;
			if (sourceContent !== undefined) {
				while (sourcesContent.length < sourceIndex) {
					sourcesContent.push(null);
				}
				sourcesContent[sourceIndex] = sourceContent;
			}
			return onSource(sourceIndex, source, sourceContent);
		},
		(nameIndex, name) => {
			while (names.length < nameIndex) {
				names.push(null);
			}
			names[nameIndex] = name;
			return onName(nameIndex, name);
		}
	);
	const resultSource = source !== undefined ? source : code;
	return {
		result: {
			generatedLine,
			generatedColumn,
			source: finalSource ? resultSource : undefined
		},
		source: resultSource,
		map:
			mappings.length > 0
				? {
						version: 3,
						file: "x",
						mappings,
						sources,
						sourcesContent:
							sourcesContent.length > 0 ? sourcesContent : undefined,
						names
				  }
				: null
	};
};

module.exports = streamAndGetSourceAndMap;


code:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

const streamChunksOfRawSource = require("./streamChunksOfRawSource");
const streamChunksOfSourceMap = require("./streamChunksOfSourceMap");

module.exports = (source, options, onChunk, onSource, onName) => {
	if (typeof source.streamChunks === "function") {
		return source.streamChunks(options, onChunk, onSource, onName);
	} else {
		const sourceAndMap = source.sourceAndMap(options);
		if (sourceAndMap.map) {
			return streamChunksOfSourceMap(
				sourceAndMap.source,
				sourceAndMap.map,
				onChunk,
				onSource,
				onName,
				!!(options && options.finalSource),
				!!(options && options.columns !== false)
			);
		} else {
			return streamChunksOfRawSource(
				sourceAndMap.source,
				onChunk,
				onSource,
				onName,
				!!(options && options.finalSource)
			);
		}
	}
};

license: mit


code:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

const streamChunksOfSourceMap = require("./streamChunksOfSourceMap");
const splitIntoLines = require("./splitIntoLines");

const streamChunksOfCombinedSourceMap = (
	source,
	sourceMap,
	innerSourceName,
	innerSource,
	innerSourceMap,
	removeInnerSource,
	onChunk,
	onSource,
	onName,
	finalSource,
	columns
) => {
	let sourceMapping = new Map();
	let nameMapping = new Map();
	const sourceIndexMapping = [];
	const nameIndexMapping = [];
	const nameIndexValueMapping = [];
	let innerSourceIndex = -2;
	const innerSourceIndexMapping = [];
	const innerSourceIndexValueMapping = [];
	const innerSourceContents = [];
	const innerSourceContentLines = [];
	const innerNameIndexMapping = [];
	const innerNameIndexValueMapping = [];
	const innerSourceMapLineData = [];
	const findInnerMapping = (line, column) => {
		if (line > innerSourceMapLineData.length) return -1;
		const { mappingsData } = innerSourceMapLineData[line - 1];
		let l = 0;
		let r = mappingsData.length / 5;
		while (l < r) {
			let m = (l + r) >> 1;
			if (mappingsData[m * 5] <= column) {
				l = m + 1;
			} else {
				r = m;
			}
		}
		if (l === 0) return -1;
		return l - 1;
	};
	return streamChunksOfSourceMap(
		source,
		sourceMap,
		(
			chunk,
			generatedLine,
			generatedColumn,
			sourceIndex,
			originalLine,
			originalColumn,
			nameIndex
		) => {
			// Check if this is a mapping to the inner source
			if (sourceIndex === innerSourceIndex) {
				// Check if there is a mapping in the inner source
				const idx = findInnerMapping(originalLine, originalColumn);
				if (idx !== -1) {
					const { chunks, mappingsData } = innerSourceMapLineData[
						originalLine - 1
					];
					const mi = idx * 5;
					const innerSourceIndex = mappingsData[mi + 1];
					const innerOriginalLine = mappingsData[mi + 2];
					let innerOriginalColumn = mappingsData[mi + 3];
					let innerNameIndex = mappingsData[mi + 4];
					if (innerSourceIndex >= 0) {
						// Check for an identity mapping
						// where we are allowed to adjust the original column
						const innerChunk = chunks[idx];
						const innerGeneratedColumn = mappingsData[mi];
						const locationInChunk = originalColumn - innerGeneratedColumn;
						if (locationInChunk > 0) {
							let originalSourceLines =
								innerSourceIndex < innerSourceContentLines.length
									? innerSourceContentLines[innerSourceIndex]
									: null;
							if (originalSourceLines === undefined) {
								const originalSource = innerSourceContents[innerSourceIndex];
								originalSourceLines = originalSource
									? splitIntoLines(originalSource)
									: null;
								innerSourceContentLines[innerSourceIndex] = originalSourceLines;
							}
							if (originalSourceLines !== null) {
								const originalChunk =
									innerOriginalLine <= originalSourceLines.length
										? originalSourceLines[innerOriginalLine - 1].slice(
												innerOriginalColumn,
												innerOriginalColumn + locationInChunk
										  )
										: "";
								if (innerChunk.slice(0, locationInChunk) === originalChunk) {
									innerOriginalColumn += locationInChunk;
									innerNameIndex = -1;
								}
							}
						}

						// We have a inner mapping to original source

						// emit source when needed and compute global source index
						let sourceIndex =
							innerSourceIndex < innerSourceIndexMapping.length
								? innerSourceIndexMapping[innerSourceIndex]
								: -2;
						if (sourceIndex === -2) {
							const [source, sourceContent] =
								innerSourceIndex < innerSourceIndexValueMapping.length
									? innerSourceIndexValueMapping[innerSourceIndex]
									: [null, undefined];
							let globalIndex = sourceMapping.get(source);
							if (globalIndex === undefined) {
								sourceMapping.set(source, (globalIndex = sourceMapping.size));
								onSource(globalIndex, source, sourceContent);
							}
							sourceIndex = globalIndex;
							innerSourceIndexMapping[innerSourceIndex] = sourceIndex;
						}

						// emit name when needed and compute global name index
						let finalNameIndex = -1;
						if (innerNameIndex >= 0) {
							// when we have a inner name
							finalNameIndex =
								innerNameIndex < innerNameIndexMapping.length
									? innerNameIndexMapping[innerNameIndex]
									: -2;
							if (finalNameIndex === -2) {
								const name =
									innerNameIndex < innerNameIndexValueMapping.length
										? innerNameIndexValueMapping[innerNameIndex]
										: undefined;
								if (name) {
									let globalIndex = nameMapping.get(name);
									if (globalIndex === undefined) {
										nameMapping.set(name, (globalIndex = nameMapping.size));
										onName(globalIndex, name);
									}
									finalNameIndex = globalIndex;
								} else {
									finalNameIndex = -1;
								}
								innerNameIndexMapping[innerNameIndex] = finalNameIndex;
							}
						} else if (nameIndex >= 0) {
							// when we don't have an inner name,
							// but we have an outer name
							// it can be used when inner original code equals to the name
							let originalSourceLines =
								innerSourceContentLines[innerSourceIndex];
							if (originalSourceLines === undefined) {
								const originalSource = innerSourceContents[innerSourceIndex];
								originalSourceLines = originalSource
									? splitIntoLines(originalSource)
									: null;
								innerSourceContentLines[innerSourceIndex] = originalSourceLines;
							}
							if (originalSourceLines !== null) {
								const name = nameIndexValueMapping[nameIndex];
								const originalName =
									innerOriginalLine <= originalSourceLines.length
										? originalSourceLines[innerOriginalLine - 1].slice(
												innerOriginalColumn,
												innerOriginalColumn + name.length
										  )
										: "";
								if (name === originalName) {
									finalNameIndex =
										nameIndex < nameIndexMapping.length
											? nameIndexMapping[nameIndex]
											: -2;
									if (finalNameIndex === -2) {
										const name = nameIndexValueMapping[nameIndex];
										if (name) {
											let globalIndex = nameMapping.get(name);
											if (globalIndex === undefined) {
												nameMapping.set(name, (globalIndex = nameMapping.size));
												onName(globalIndex, name);
											}
											finalNameIndex = globalIndex;
										} else {
											finalNameIndex = -1;
										}
										nameIndexMapping[nameIndex] = finalNameIndex;
									}
								}
							}
						}
						onChunk(
							chunk,
							generatedLine,
							generatedColumn,
							sourceIndex,
							innerOriginalLine,
							innerOriginalColumn,
							finalNameIndex
						);
						return;
					}
				}

				// We have a mapping to the inner source, but no inner mapping
				if (removeInnerSource) {
					onChunk(chunk, generatedLine, generatedColumn, -1, -1, -1, -1);
					return;
				} else {
					if (sourceIndexMapping[sourceIndex] === -2) {
						let globalIndex = sourceMapping.get(innerSourceName);
						if (globalIndex === undefined) {
							sourceMapping.set(source, (globalIndex = sourceMapping.size));
							onSource(globalIndex, innerSourceName, innerSource);
						}
						sourceIndexMapping[sourceIndex] = globalIndex;
					}
				}
			}

			const finalSourceIndex =
				sourceIndex < 0 || sourceIndex >= sourceIndexMapping.length
					? -1
					: sourceIndexMapping[sourceIndex];
			if (finalSourceIndex < 0) {
				// no source, so we make it a generated chunk
				onChunk(chunk, generatedLine, generatedColumn, -1, -1, -1, -1);
			} else {
				// Pass through the chunk with mapping
				let finalNameIndex = -1;
				if (nameIndex >= 0 && nameIndex < nameIndexMapping.length) {
					finalNameIndex = nameIndexMapping[nameIndex];
					if (finalNameIndex === -2) {
						const name = nameIndexValueMapping[nameIndex];
						let globalIndex = nameMapping.get(name);
						if (globalIndex === undefined) {
							nameMapping.set(name, (globalIndex = nameMapping.size));
							onName(globalIndex, name);
						}
						finalNameIndex = globalIndex;
						nameIndexMapping[nameIndex] = finalNameIndex;
					}
				}
				onChunk(
					chunk,
					generatedLine,
					generatedColumn,
					finalSourceIndex,
					originalLine,
					originalColumn,
					finalNameIndex
				);
			}
		},
		(i, source, sourceContent) => {
			if (source === innerSourceName) {
				innerSourceIndex = i;
				if (innerSource !== undefined) sourceContent = innerSource;
				else innerSource = sourceContent;
				sourceIndexMapping[i] = -2;
				streamChunksOfSourceMap(
					sourceContent,
					innerSourceMap,
					(
						chunk,
						generatedLine,
						generatedColumn,
						sourceIndex,
						originalLine,
						originalColumn,
						nameIndex
					) => {
						while (innerSourceMapLineData.length < generatedLine) {
							innerSourceMapLineData.push({
								mappingsData: [],
								chunks: []
							});
						}
						const data = innerSourceMapLineData[generatedLine - 1];
						data.mappingsData.push(
							generatedColumn,
							sourceIndex,
							originalLine,
							originalColumn,
							nameIndex
						);
						data.chunks.push(chunk);
					},
					(i, source, sourceContent) => {
						innerSourceContents[i] = sourceContent;
						innerSourceContentLines[i] = undefined;
						innerSourceIndexMapping[i] = -2;
						innerSourceIndexValueMapping[i] = [source, sourceContent];
					},
					(i, name) => {
						innerNameIndexMapping[i] = -2;
						innerNameIndexValueMapping[i] = name;
					},
					false,
					columns
				);
			} else {
				let globalIndex = sourceMapping.get(source);
				if (globalIndex === undefined) {
					sourceMapping.set(source, (globalIndex = sourceMapping.size));
					onSource(globalIndex, source, sourceContent);
				}
				sourceIndexMapping[i] = globalIndex;
			}
		},
		(i, name) => {
			nameIndexMapping[i] = -2;
			nameIndexValueMapping[i] = name;
		},
		finalSource,
		columns
	);
};

module.exports = streamChunksOfCombinedSourceMap;


code:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

const getGeneratedSourceInfo = require("./getGeneratedSourceInfo");
const splitIntoLines = require("./splitIntoLines");

const streamChunksOfRawSource = (source, onChunk, onSource, onName) => {
	let line = 1;
	const matches = splitIntoLines(source);
	let match;
	for (match of matches) {
		onChunk(match, line, 0, -1, -1, -1, -1);
		line++;
	}
	return matches.length === 0 || match.endsWith("\n")
		? {
				generatedLine: matches.length + 1,
				generatedColumn: 0
		  }
		: {
				generatedLine: matches.length,
				generatedColumn: match.length
		  };
};

module.exports = (source, onChunk, onSource, onName, finalSource) => {
	return finalSource
		? getGeneratedSourceInfo(source)
		: streamChunksOfRawSource(source, onChunk, onSource, onName);
};


code:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

const getGeneratedSourceInfo = require("./getGeneratedSourceInfo");
const getSource = require("./getSource");
const readMappings = require("./readMappings");
const splitIntoLines = require("./splitIntoLines");

const streamChunksOfSourceMapFull = (
	source,
	sourceMap,
	onChunk,
	onSource,
	onName
) => {
	const lines = splitIntoLines(source);
	if (lines.length === 0) {
		return {
			generatedLine: 1,
			generatedColumn: 0
		};
	}
	const { sources, sourcesContent, names, mappings } = sourceMap;
	for (let i = 0; i < sources.length; i++) {
		onSource(
			i,
			getSource(sourceMap, i),
			(sourcesContent && sourcesContent[i]) || undefined
		);
	}
	if (names) {
		for (let i = 0; i < names.length; i++) {
			onName(i, names[i]);
		}
	}

	const lastLine = lines[lines.length - 1];
	const lastNewLine = lastLine.endsWith("\n");
	const finalLine = lastNewLine ? lines.length + 1 : lines.length;
	const finalColumn = lastNewLine ? 0 : lastLine.length;

	let currentGeneratedLine = 1;
	let currentGeneratedColumn = 0;

	let mappingActive = false;
	let activeMappingSourceIndex = -1;
	let activeMappingOriginalLine = -1;
	let activeMappingOriginalColumn = -1;
	let activeMappingNameIndex = -1;

	const onMapping = (
		generatedLine,
		generatedColumn,
		sourceIndex,
		originalLine,
		originalColumn,
		nameIndex
	) => {
		if (mappingActive && currentGeneratedLine <= lines.length) {
			let chunk;
			const mappingLine = currentGeneratedLine;
			const mappingColumn = currentGeneratedColumn;
			const line = lines[currentGeneratedLine - 1];
			if (generatedLine !== currentGeneratedLine) {
				chunk = line.slice(currentGeneratedColumn);
				currentGeneratedLine++;
				currentGeneratedColumn = 0;
			} else {
				chunk = line.slice(currentGeneratedColumn, generatedColumn);
				currentGeneratedColumn = generatedColumn;
			}
			if (chunk) {
				onChunk(
					chunk,
					mappingLine,
					mappingColumn,
					activeMappingSourceIndex,
					activeMappingOriginalLine,
					activeMappingOriginalColumn,
					activeMappingNameIndex
				);
			}
			mappingActive = false;
		}
		if (generatedLine > currentGeneratedLine && currentGeneratedColumn > 0) {
			if (currentGeneratedLine <= lines.length) {
				const chunk = lines[currentGeneratedLine - 1].slice(
					currentGeneratedColumn
				);
				onChunk(
					chunk,
					currentGeneratedLine,
					currentGeneratedColumn,
					-1,
					-1,
					-1,
					-1
				);
			}
			currentGeneratedLine++;
			currentGeneratedColumn = 0;
		}
		while (generatedLine > currentGeneratedLine) {
			if (currentGeneratedLine <= lines.length) {
				onChunk(
					lines[currentGeneratedLine - 1],
					currentGeneratedLine,
					0,
					-1,
					-1,
					-1,
					-1
				);
			}
			currentGeneratedLine++;
		}
		if (generatedColumn > currentGeneratedColumn) {
			if (currentGeneratedLine <= lines.length) {
				const chunk = lines[currentGeneratedLine - 1].slice(
					currentGeneratedColumn,
					generatedColumn
				);
				onChunk(
					chunk,
					currentGeneratedLine,
					currentGeneratedColumn,
					-1,
					-1,
					-1,
					-1
				);
			}
			currentGeneratedColumn = generatedColumn;
		}
		if (
			sourceIndex >= 0 &&
			(generatedLine < finalLine ||
				(generatedLine === finalLine && generatedColumn < finalColumn))
		) {
			mappingActive = true;
			activeMappingSourceIndex = sourceIndex;
			activeMappingOriginalLine = originalLine;
			activeMappingOriginalColumn = originalColumn;
			activeMappingNameIndex = nameIndex;
		}
	};
	readMappings(mappings, onMapping);
	onMapping(finalLine, finalColumn, -1, -1, -1, -1);
	return {
		generatedLine: finalLine,
		generatedColumn: finalColumn
	};
};

const streamChunksOfSourceMapLinesFull = (
	source,
	sourceMap,
	onChunk,
	onSource,
	_onName
) => {
	const lines = splitIntoLines(source);
	if (lines.length === 0) {
		return {
			generatedLine: 1,
			generatedColumn: 0
		};
	}
	const { sources, sourcesContent, mappings } = sourceMap;
	for (let i = 0; i < sources.length; i++) {
		onSource(
			i,
			getSource(sourceMap, i),
			(sourcesContent && sourcesContent[i]) || undefined
		);
	}

	let currentGeneratedLine = 1;

	const onMapping = (
		generatedLine,
		_generatedColumn,
		sourceIndex,
		originalLine,
		originalColumn,
		_nameIndex
	) => {
		if (
			sourceIndex < 0 ||
			generatedLine < currentGeneratedLine ||
			generatedLine > lines.length
		) {
			return;
		}
		while (generatedLine > currentGeneratedLine) {
			if (currentGeneratedLine <= lines.length) {
				onChunk(
					lines[currentGeneratedLine - 1],
					currentGeneratedLine,
					0,
					-1,
					-1,
					-1,
					-1
				);
			}
			currentGeneratedLine++;
		}
		if (generatedLine <= lines.length) {
			onChunk(
				lines[generatedLine - 1],
				generatedLine,
				0,
				sourceIndex,
				originalLine,
				originalColumn,
				-1
			);
			currentGeneratedLine++;
		}
	};
	readMappings(mappings, onMapping);
	for (; currentGeneratedLine <= lines.length; currentGeneratedLine++) {
		onChunk(
			lines[currentGeneratedLine - 1],
			currentGeneratedLine,
			0,
			-1,
			-1,
			-1,
			-1
		);
	}

	const lastLine = lines[lines.length - 1];
	const lastNewLine = lastLine.endsWith("\n");

	const finalLine = lastNewLine ? lines.length + 1 : lines.length;
	const finalColumn = lastNewLine ? 0 : lastLine.length;

	return {
		generatedLine: finalLine,
		generatedColumn: finalColumn
	};
};

const streamChunksOfSourceMapFinal = (
	source,
	sourceMap,
	onChunk,
	onSource,
	onName
) => {
	const result = getGeneratedSourceInfo(source);
	const { generatedLine: finalLine, generatedColumn: finalColumn } = result;

	if (finalLine === 1 && finalColumn === 0) return result;
	const { sources, sourcesContent, names, mappings } = sourceMap;
	for (let i = 0; i < sources.length; i++) {
		onSource(
			i,
			getSource(sourceMap, i),
			(sourcesContent && sourcesContent[i]) || undefined
		);
	}
	if (names) {
		for (let i = 0; i < names.length; i++) {
			onName(i, names[i]);
		}
	}

	let mappingActiveLine = 0;

	const onMapping = (
		generatedLine,
		generatedColumn,
		sourceIndex,
		originalLine,
		originalColumn,
		nameIndex
	) => {
		if (
			generatedLine >= finalLine &&
			(generatedColumn >= finalColumn || generatedLine > finalLine)
		) {
			return;
		}
		if (sourceIndex >= 0) {
			onChunk(
				undefined,
				generatedLine,
				generatedColumn,
				sourceIndex,
				originalLine,
				originalColumn,
				nameIndex
			);
			mappingActiveLine = generatedLine;
		} else if (mappingActiveLine === generatedLine) {
			onChunk(undefined, generatedLine, generatedColumn, -1, -1, -1, -1);
			mappingActiveLine = 0;
		}
	};
	readMappings(mappings, onMapping);
	return result;
};

const streamChunksOfSourceMapLinesFinal = (
	source,
	sourceMap,
	onChunk,
	onSource,
	_onName
) => {
	const result = getGeneratedSourceInfo(source);
	const { generatedLine, generatedColumn } = result;
	if (generatedLine === 1 && generatedColumn === 0) {
		return {
			generatedLine: 1,
			generatedColumn: 0
		};
	}

	const { sources, sourcesContent, mappings } = sourceMap;
	for (let i = 0; i < sources.length; i++) {
		onSource(
			i,
			getSource(sourceMap, i),
			(sourcesContent && sourcesContent[i]) || undefined
		);
	}

	const finalLine = generatedColumn === 0 ? generatedLine - 1 : generatedLine;

	let currentGeneratedLine = 1;

	const onMapping = (
		generatedLine,
		_generatedColumn,
		sourceIndex,
		originalLine,
		originalColumn,
		_nameIndex
	) => {
		if (
			sourceIndex >= 0 &&
			currentGeneratedLine <= generatedLine &&
			generatedLine <= finalLine
		) {
			onChunk(
				undefined,
				generatedLine,
				0,
				sourceIndex,
				originalLine,
				originalColumn,
				-1
			);
			currentGeneratedLine = generatedLine + 1;
		}
	};
	readMappings(mappings, onMapping);
	return result;
};

module.exports = (
	source,
	sourceMap,
	onChunk,
	onSource,
	onName,
	finalSource,
	columns
) => {
	if (columns) {
		return finalSource
			? streamChunksOfSourceMapFinal(
					source,
					sourceMap,
					onChunk,
					onSource,
					onName
			  )
			: streamChunksOfSourceMapFull(
					source,
					sourceMap,
					onChunk,
					onSource,
					onName
			  );
	} else {
		return finalSource
			? streamChunksOfSourceMapLinesFinal(
					source,
					sourceMap,
					onChunk,
					onSource,
					onName
			  )
			: streamChunksOfSourceMapLinesFull(
					source,
					sourceMap,
					onChunk,
					onSource,
					onName
			  );
	}
};


code:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

const defineExport = (name, fn) => {
	let value;
	Object.defineProperty(exports, name, {
		get: () => {
			if (fn !== undefined) {
				value = fn();
				fn = undefined;
			}
			return value;
		},
		configurable: true
	});
};

defineExport("Source", () => require("./Source"));

defineExport("RawSource", () => require("./RawSource"));
defineExport("OriginalSource", () => require("./OriginalSource"));
defineExport("SourceMapSource", () => require("./SourceMapSource"));
defineExport("CachedSource", () => require("./CachedSource"));
defineExport("ConcatSource", () => require("./ConcatSource"));
defineExport("ReplaceSource", () => require("./ReplaceSource"));
defineExport("PrefixSource", () => require("./PrefixSource"));
defineExport("SizeOnlySource", () => require("./SizeOnlySource"));
defineExport("CompatSource", () => require("./CompatSource"));


webpack-sources

description: Source code handling classes for webpack

pretest: yarn lint

test: jest

lint: eslint --cache lib test/*.js

cover: jest --coverage

type: git

keywords: webpack source-map

author: Tobias Koppers @sokra

license: MIT

testEnvironment: node


code:
# Webpack Virtual Modules

[![Build Status](https://travis-ci.org/sysgears/webpack-virtual-modules.svg?branch=master)](https://travis-ci.org/sysgears/webpack-virtual-modules)
[![Twitter Follow](https://img.shields.io/twitter/follow/sysgears.svg?style=social)](https://twitter.com/sysgears)

**Webpack Virtual Modules** is a plugin that allows for dynamical generation of in-memory virtual modules for JavaScript
builds created with webpack. When virtual module is created all the parent virtual dirs that lead to the module filename are created too. This plugin supports watch mode meaning any write to a virtual module is seen by webpack as
if a real file stored on disk has changed.

## Installation

Use NPM or Yarn to install Webpack Virtual Modules as a development dependency:

```bash
# with NPM
npm install webpack-virtual-modules --save-dev

# with Yarn
yarn add webpack-virtual-modules --dev
```

## Usage

You can use Webpack Virtual Modules with webpack 5, 4 and 3. The examples below show the usage with webpack 5 or 4. If you want to use our plugin with webpack 3, check out a dedicated doc:

* [Webpack Virtual Modules with Webpack 3]

### Generating static virtual modules

Require the plugin in the webpack configuration file, then create and add virtual modules in the `plugins` array in the
webpack configuration object:

```js
var VirtualModulesPlugin = require('webpack-virtual-modules');

var virtualModules = new VirtualModulesPlugin({
  'node_modules/module-foo.js': 'module.exports = { foo: "foo" };',
  'node_modules/module-bar.js': 'module.exports = { bar: "bar" };'
});

module.exports = {
  // ...
  plugins: [
    virtualModules
  ]
};
```

You can now import your virtual modules anywhere in the application and use them:

```js
var moduleFoo = require('module-foo');
// You can now use moduleFoo
console.log(moduleFoo.foo);
```

### Generating dynamic virtual modules

You can generate virtual modules **_dynamically_** with Webpack Virtual Modules.

Here's an example of dynamic generation of a module. All you need to do is create new virtual modules using the plugin
and add them to the `plugins` array. After that, you need to add a webpack hook. For using hooks, consult [webpack
compiler hook documentation].

```js
var webpack = require('webpack');
var VirtualModulesPlugin = require('webpack-virtual-modules');

// Create an empty set of virtual modules
const virtualModules = new VirtualModulesPlugin();

var compiler = webpack({
  // ...
  plugins: [
    virtualModules
  ]
});

compiler.hooks.compilation.tap('MyPlugin', function(compilation) {
  virtualModules.writeModule('node_modules/module-foo.js', '');
});

compiler.watch();
```

In other module or a Webpack plugin, you can write to the module `module-foo` whatever you need. After this write,
webpack will "see" that `module-foo.js` has changed and will restart compilation.

```js
virtualModules.writeModule(
  'node_modules/module-foo.js',
  'module.exports = { foo: "foo" };'
);
```

## More Examples

  - [Swagger and JSDoc Example with Webpack 5]
  - [Swagger and JSDoc Example with Webpack 4]
  - [Swagger and JSDoc Example with Webpack 3]

## API Reference

  - [API Reference]

## Inspiration

This project is inspired by [virtual-module-webpack-plugin].

## License

Copyright © 2017 [SysGears INC]. This source code is licensed under the [MIT] license.

[webpack virtual modules with webpack 3]: https://github.com/sysgears/webpack-virtual-modules/tree/master/docs/webpack3.md
[webpack compiler hook documentation]: https://webpack.js.org/api/compiler-hooks/
[swagger and jsdoc example with webpack 3]: https://github.com/sysgears/webpack-virtual-modules/tree/master/examples/swagger-webpack3
[swagger and jsdoc example with webpack 4]: https://github.com/sysgears/webpack-virtual-modules/tree/master/examples/swagger-webpack4
[swagger and jsdoc example with webpack 5]: https://github.com/sysgears/webpack-virtual-modules/tree/master/examples/swagger-webpack5
[api reference]: https://github.com/sysgears/webpack-virtual-modules/tree/master/docs/API%20Reference.md
[virtual-module-webpack-plugin]: https://github.com/rmarscher/virtual-module-webpack-plugin
[MIT]: LICENSE
[SysGears INC]: http://sysgears.com


code:
import type { Compiler } from 'webpack';
declare class VirtualModulesPlugin {
    private _staticModules;
    private _compiler;
    private _watcher;
    constructor(modules?: Record<string, string>);
    writeModule(filePath: string, contents: string): void;
    apply(compiler: Compiler): void;
}
export = VirtualModulesPlugin;


code:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
const path_1 = __importDefault(require("path"));
const virtual_stats_1 = require("./virtual-stats");
let inode = 45000000;
function checkActivation(instance) {
    if (!instance._compiler) {
        throw new Error('You must use this plugin only after creating webpack instance!');
    }
}
function getModulePath(filePath, compiler) {
    return path_1.default.isAbsolute(filePath) ? filePath : path_1.default.join(compiler.context, filePath);
}
function createWebpackData(result) {
    return (backendOrStorage) => {
        if (backendOrStorage._data) {
            const curLevelIdx = backendOrStorage._currentLevel;
            const curLevel = backendOrStorage._levels[curLevelIdx];
            return {
                result,
                level: curLevel,
            };
        }
        return [null, result];
    };
}
function getData(storage, key) {
    if (storage._data instanceof Map) {
        return storage._data.get(key);
    }
    else if (storage._data) {
        return storage.data[key];
    }
    else if (storage.data instanceof Map) {
        return storage.data.get(key);
    }
    else {
        return storage.data[key];
    }
}
function setData(backendOrStorage, key, valueFactory) {
    const value = valueFactory(backendOrStorage);
    if (backendOrStorage._data instanceof Map) {
        backendOrStorage._data.set(key, value);
    }
    else if (backendOrStorage._data) {
        backendOrStorage.data[key] = value;
    }
    else if (backendOrStorage.data instanceof Map) {
        backendOrStorage.data.set(key, value);
    }
    else {
        backendOrStorage.data[key] = value;
    }
}
function getStatStorage(fileSystem) {
    if (fileSystem._statStorage) {
        return fileSystem._statStorage;
    }
    else if (fileSystem._statBackend) {
        return fileSystem._statBackend;
    }
    else {
        throw new Error("Couldn't find a stat storage");
    }
}
function getFileStorage(fileSystem) {
    if (fileSystem._readFileStorage) {
        return fileSystem._readFileStorage;
    }
    else if (fileSystem._readFileBackend) {
        return fileSystem._readFileBackend;
    }
    else {
        throw new Error("Couldn't find a readFileStorage");
    }
}
function getReadDirBackend(fileSystem) {
    if (fileSystem._readdirBackend) {
        return fileSystem._readdirBackend;
    }
    else if (fileSystem._readdirStorage) {
        return fileSystem._readdirStorage;
    }
    else {
        throw new Error("Couldn't find a readDirStorage from Webpack Internals");
    }
}
class VirtualModulesPlugin {
    constructor(modules) {
        this._compiler = null;
        this._watcher = null;
        this._staticModules = modules || null;
    }
    writeModule(filePath, contents) {
        if (!this._compiler) {
            throw new Error(`Plugin has not been initialized`);
        }
        checkActivation(this);
        const len = contents ? contents.length : 0;
        const time = Date.now();
        const date = new Date(time);
        const stats = new virtual_stats_1.VirtualStats({
            dev: 8675309,
            nlink: 0,
            uid: 1000,
            gid: 1000,
            rdev: 0,
            blksize: 4096,
            ino: inode++,
            mode: 33188,
            size: len,
            blocks: Math.floor(len / 4096),
            atime: date,
            mtime: date,
            ctime: date,
            birthtime: date,
        });
        const modulePath = getModulePath(filePath, this._compiler);
        if (process.env.WVM_DEBUG)
            console.log(this._compiler.name, 'Write virtual module:', modulePath, contents);
        let finalWatchFileSystem = this._watcher && this._watcher.watchFileSystem;
        while (finalWatchFileSystem && finalWatchFileSystem.wfs) {
            finalWatchFileSystem = finalWatchFileSystem.wfs;
        }
        let finalInputFileSystem = this._compiler.inputFileSystem;
        while (finalInputFileSystem && finalInputFileSystem._inputFileSystem) {
            finalInputFileSystem = finalInputFileSystem._inputFileSystem;
        }
        finalInputFileSystem._writeVirtualFile(modulePath, stats, contents);
        if (finalWatchFileSystem &&
            (finalWatchFileSystem.watcher.fileWatchers.size || finalWatchFileSystem.watcher.fileWatchers.length)) {
            const fileWatchers = finalWatchFileSystem.watcher.fileWatchers instanceof Map
                ? Array.from(finalWatchFileSystem.watcher.fileWatchers.values())
                : finalWatchFileSystem.watcher.fileWatchers;
            for (let fileWatcher of fileWatchers) {
                if ('watcher' in fileWatcher) {
                    fileWatcher = fileWatcher.watcher;
                }
                if (fileWatcher.path === modulePath) {
                    if (process.env.DEBUG)
                        console.log(this._compiler.name, 'Emit file change:', modulePath, time);
                    delete fileWatcher.directoryWatcher._cachedTimeInfoEntries;
                    fileWatcher.emit('change', time, null);
                }
            }
        }
    }
    apply(compiler) {
        this._compiler = compiler;
        const afterEnvironmentHook = () => {
            let finalInputFileSystem = compiler.inputFileSystem;
            while (finalInputFileSystem && finalInputFileSystem._inputFileSystem) {
                finalInputFileSystem = finalInputFileSystem._inputFileSystem;
            }
            if (!finalInputFileSystem._writeVirtualFile) {
                const originalPurge = finalInputFileSystem.purge;
                finalInputFileSystem.purge = () => {
                    originalPurge.apply(finalInputFileSystem, []);
                    if (finalInputFileSystem._virtualFiles) {
                        Object.keys(finalInputFileSystem._virtualFiles).forEach((file) => {
                            const data = finalInputFileSystem._virtualFiles[file];
                            finalInputFileSystem._writeVirtualFile(file, data.stats, data.contents);
                        });
                    }
                };
                finalInputFileSystem._writeVirtualFile = (file, stats, contents) => {
                    const statStorage = getStatStorage(finalInputFileSystem);
                    const fileStorage = getFileStorage(finalInputFileSystem);
                    const readDirStorage = getReadDirBackend(finalInputFileSystem);
                    finalInputFileSystem._virtualFiles = finalInputFileSystem._virtualFiles || {};
                    finalInputFileSystem._virtualFiles[file] = { stats: stats, contents: contents };
                    setData(statStorage, file, createWebpackData(stats));
                    setData(fileStorage, file, createWebpackData(contents));
                    const segments = file.split(/[\\/]/);
                    let count = segments.length - 1;
                    const minCount = segments[0] ? 1 : 0;
                    while (count > minCount) {
                        const dir = segments.slice(0, count).join(path_1.default.sep) || path_1.default.sep;
                        try {
                            finalInputFileSystem.readdirSync(dir);
                        }
                        catch (e) {
                            const time = Date.now();
                            const dirStats = new virtual_stats_1.VirtualStats({
                                dev: 8675309,
                                nlink: 0,
                                uid: 1000,
                                gid: 1000,
                                rdev: 0,
                                blksize: 4096,
                                ino: inode++,
                                mode: 16877,
                                size: stats.size,
                                blocks: Math.floor(stats.size / 4096),
                                atime: time,
                                mtime: time,
                                ctime: time,
                                birthtime: time,
                            });
                            setData(readDirStorage, dir, createWebpackData([]));
                            setData(statStorage, dir, createWebpackData(dirStats));
                        }
                        let dirData = getData(getReadDirBackend(finalInputFileSystem), dir);
                        dirData = dirData[1] || dirData.result;
                        const filename = segments[count];
                        if (dirData.indexOf(filename) < 0) {
                            const files = dirData.concat([filename]).sort();
                            setData(getReadDirBackend(finalInputFileSystem), dir, createWebpackData(files));
                        }
                        else {
                            break;
                        }
                        count--;
                    }
                };
            }
        };
        const afterResolversHook = () => {
            if (this._staticModules) {
                for (const [filePath, contents] of Object.entries(this._staticModules)) {
                    this.writeModule(filePath, contents);
                }
                this._staticModules = null;
            }
        };
        const watchRunHook = (watcher, callback) => {
            this._watcher = watcher.compiler || watcher;
            const virtualFiles = compiler.inputFileSystem._virtualFiles;
            const fts = compiler.fileTimestamps;
            if (virtualFiles && fts && typeof fts.set === 'function') {
                Object.keys(virtualFiles).forEach((file) => {
                    fts.set(file, +virtualFiles[file].stats.mtime);
                });
            }
            callback();
        };
        if (compiler.hooks) {
            compiler.hooks.afterEnvironment.tap('VirtualModulesPlugin', afterEnvironmentHook);
            compiler.hooks.afterResolvers.tap('VirtualModulesPlugin', afterResolversHook);
            compiler.hooks.watchRun.tapAsync('VirtualModulesPlugin', watchRunHook);
        }
        else {
            compiler.plugin('after-environment', afterEnvironmentHook);
            compiler.plugin('after-resolvers', afterResolversHook);
            compiler.plugin('watch-run', watchRunHook);
        }
    }
}
module.exports = VirtualModulesPlugin;
//# sourceMappingURL=index.js.map


code:
export declare class VirtualStats {
    constructor(config: any);
    private _checkModeProperty;
    isDirectory(): boolean;
    isFile(): boolean;
    isBlockDevice(): boolean;
    isCharacterDevice(): boolean;
    isSymbolicLink(): boolean;
    isFIFO(): boolean;
    isSocket(): boolean;
}


code:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.VirtualStats = void 0;
const constants_1 = __importDefault(require("constants"));
class VirtualStats {
    constructor(config) {
        for (const key in config) {
            if (!Object.prototype.hasOwnProperty.call(config, key)) {
                continue;
            }
            this[key] = config[key];
        }
    }
    _checkModeProperty(property) {
        return (this.mode & constants_1.default.S_IFMT) === property;
    }
    isDirectory() {
        return this._checkModeProperty(constants_1.default.S_IFDIR);
    }
    isFile() {
        return this._checkModeProperty(constants_1.default.S_IFREG);
    }
    isBlockDevice() {
        return this._checkModeProperty(constants_1.default.S_IFBLK);
    }
    isCharacterDevice() {
        return this._checkModeProperty(constants_1.default.S_IFCHR);
    }
    isSymbolicLink() {
        return this._checkModeProperty(constants_1.default.S_IFLNK);
    }
    isFIFO() {
        return this._checkModeProperty(constants_1.default.S_IFIFO);
    }
    isSocket() {
        return this._checkModeProperty(constants_1.default.S_IFSOCK);
    }
}
exports.VirtualStats = VirtualStats;
//# sourceMappingURL=virtual-stats.js.map


webpack-virtual-modules

description: Webpack Virtual Modules

clean: rm -rf ./lib

build: tsc -p tsconfig.build.json

watch: tsc -p tsconfig.build.json -w

tests: jest

tests:watch: jest --watch

test: yarn lint && yarn tests

lint: eslint --fix src/**/*.ts

prepack: yarn clean && yarn build

keywords: webpack webpack-plugin virtual modules

author: SysGears INC

files: lib src !__tests__

*.ts:
eslint --fix -c tslint.json
git add

parser: typescript

pre-commit: lint-staged


code:
import path from 'path';
import { VirtualStats } from './virtual-stats';
import type { Compiler } from 'webpack';

let inode = 45000000;

function checkActivation(instance) {
  if (!instance._compiler) {
    throw new Error('You must use this plugin only after creating webpack instance!');
  }
}

function getModulePath(filePath, compiler) {
  return path.isAbsolute(filePath) ? filePath : path.join(compiler.context, filePath);
}

function createWebpackData(result) {
  return (backendOrStorage) => {
    // In Webpack v5, this variable is a "Backend", and has the data stored in a field
    // _data. In V4, the `_` prefix isn't present.
    if (backendOrStorage._data) {
      const curLevelIdx = backendOrStorage._currentLevel;
      const curLevel = backendOrStorage._levels[curLevelIdx];
      return {
        result,
        level: curLevel,
      };
    }
    // Webpack 4
    return [null, result];
  };
}

function getData(storage, key) {
  // Webpack 5
  if (storage._data instanceof Map) {
    return storage._data.get(key);
  } else if (storage._data) {
    return storage.data[key];
  } else if (storage.data instanceof Map) {
    // Webpack v4
    return storage.data.get(key);
  } else {
    return storage.data[key];
  }
}

function setData(backendOrStorage, key, valueFactory) {
  const value = valueFactory(backendOrStorage);

  // Webpack v5
  if (backendOrStorage._data instanceof Map) {
    backendOrStorage._data.set(key, value);
  } else if (backendOrStorage._data) {
    backendOrStorage.data[key] = value;
  } else if (backendOrStorage.data instanceof Map) {
    // Webpack 4
    backendOrStorage.data.set(key, value);
  } else {
    backendOrStorage.data[key] = value;
  }
}

function getStatStorage(fileSystem) {
  if (fileSystem._statStorage) {
    // Webpack v4
    return fileSystem._statStorage;
  } else if (fileSystem._statBackend) {
    // webpack v5
    return fileSystem._statBackend;
  } else {
    // Unknown version?
    throw new Error("Couldn't find a stat storage");
  }
}

function getFileStorage(fileSystem) {
  if (fileSystem._readFileStorage) {
    // Webpack v4
    return fileSystem._readFileStorage;
  } else if (fileSystem._readFileBackend) {
    // Webpack v5
    return fileSystem._readFileBackend;
  } else {
    throw new Error("Couldn't find a readFileStorage");
  }
}

function getReadDirBackend(fileSystem) {
  if (fileSystem._readdirBackend) {
    return fileSystem._readdirBackend;
  } else if (fileSystem._readdirStorage) {
    return fileSystem._readdirStorage;
  } else {
    throw new Error("Couldn't find a readDirStorage from Webpack Internals");
  }
}

class VirtualModulesPlugin {
  private _staticModules: Record<string, string> | null;
  private _compiler: Compiler | null = null;
  private _watcher: any = null;

  public constructor(modules?: Record<string, string>) {
    this._staticModules = modules || null;
  }

  public writeModule(filePath: string, contents: string): void {
    if (!this._compiler) {
      throw new Error(`Plugin has not been initialized`);
    }

    checkActivation(this);

    const len = contents ? contents.length : 0;
    const time = Date.now();
    const date = new Date(time);

    const stats = new VirtualStats({
      dev: 8675309,
      nlink: 0,
      uid: 1000,
      gid: 1000,
      rdev: 0,
      blksize: 4096,
      ino: inode++,
      mode: 33188,
      size: len,
      blocks: Math.floor(len / 4096),
      atime: date,
      mtime: date,
      ctime: date,
      birthtime: date,
    });
    const modulePath = getModulePath(filePath, this._compiler);

    if (process.env.WVM_DEBUG)
      // eslint-disable-next-line no-console
      console.log(this._compiler.name, 'Write virtual module:', modulePath, contents);

    // When using the WatchIgnorePlugin (https://github.com/webpack/webpack/blob/52184b897f40c75560b3630e43ca642fcac7e2cf/lib/WatchIgnorePlugin.js),
    // the original watchFileSystem is stored in `wfs`. The following "unwraps" the ignoring
    // wrappers, giving us access to the "real" watchFileSystem.
    let finalWatchFileSystem = this._watcher && this._watcher.watchFileSystem;

    while (finalWatchFileSystem && finalWatchFileSystem.wfs) {
      finalWatchFileSystem = finalWatchFileSystem.wfs;
    }

    let finalInputFileSystem: any = this._compiler.inputFileSystem;
    while (finalInputFileSystem && finalInputFileSystem._inputFileSystem) {
      finalInputFileSystem = finalInputFileSystem._inputFileSystem;
    }

    finalInputFileSystem._writeVirtualFile(modulePath, stats, contents);
    if (
      finalWatchFileSystem &&
      (finalWatchFileSystem.watcher.fileWatchers.size || finalWatchFileSystem.watcher.fileWatchers.length)
    ) {
      const fileWatchers =
        finalWatchFileSystem.watcher.fileWatchers instanceof Map
          ? Array.from(finalWatchFileSystem.watcher.fileWatchers.values())
          : finalWatchFileSystem.watcher.fileWatchers;
      for (let fileWatcher of fileWatchers) {
        if ('watcher' in fileWatcher) {
          fileWatcher = fileWatcher.watcher;
        }
        if (fileWatcher.path === modulePath) {
          if (process.env.DEBUG)
            // eslint-disable-next-line no-console
            console.log(this._compiler.name, 'Emit file change:', modulePath, time);
          delete fileWatcher.directoryWatcher._cachedTimeInfoEntries;
          fileWatcher.emit('change', time, null);
        }
      }
    }
  }

  public apply(compiler: Compiler) {
    this._compiler = compiler;

    const afterEnvironmentHook = () => {
      let finalInputFileSystem: any = compiler.inputFileSystem;
      while (finalInputFileSystem && finalInputFileSystem._inputFileSystem) {
        finalInputFileSystem = finalInputFileSystem._inputFileSystem;
      }

      if (!finalInputFileSystem._writeVirtualFile) {
        const originalPurge = finalInputFileSystem.purge;

        finalInputFileSystem.purge = () => {
          originalPurge.apply(finalInputFileSystem, []);
          if (finalInputFileSystem._virtualFiles) {
            Object.keys(finalInputFileSystem._virtualFiles).forEach((file) => {
              const data = finalInputFileSystem._virtualFiles[file];
              finalInputFileSystem._writeVirtualFile(file, data.stats, data.contents);
            });
          }
        };

        finalInputFileSystem._writeVirtualFile = (file, stats, contents) => {
          const statStorage = getStatStorage(finalInputFileSystem);
          const fileStorage = getFileStorage(finalInputFileSystem);
          const readDirStorage = getReadDirBackend(finalInputFileSystem);
          finalInputFileSystem._virtualFiles = finalInputFileSystem._virtualFiles || {};
          finalInputFileSystem._virtualFiles[file] = { stats: stats, contents: contents };
          setData(statStorage, file, createWebpackData(stats));
          setData(fileStorage, file, createWebpackData(contents));
          const segments = file.split(/[\\/]/);
          let count = segments.length - 1;
          const minCount = segments[0] ? 1 : 0;
          while (count > minCount) {
            const dir = segments.slice(0, count).join(path.sep) || path.sep;
            try {
              finalInputFileSystem.readdirSync(dir);
            } catch (e) {
              const time = Date.now();
              const dirStats = new VirtualStats({
                dev: 8675309,
                nlink: 0,
                uid: 1000,
                gid: 1000,
                rdev: 0,
                blksize: 4096,
                ino: inode++,
                mode: 16877,
                size: stats.size,
                blocks: Math.floor(stats.size / 4096),
                atime: time,
                mtime: time,
                ctime: time,
                birthtime: time,
              });

              setData(readDirStorage, dir, createWebpackData([]));
              setData(statStorage, dir, createWebpackData(dirStats));
            }
            let dirData = getData(getReadDirBackend(finalInputFileSystem), dir);
            // Webpack v4 returns an array, webpack v5 returns an object
            dirData = dirData[1] || dirData.result;
            const filename = segments[count];
            if (dirData.indexOf(filename) < 0) {
              const files = dirData.concat([filename]).sort();
              setData(getReadDirBackend(finalInputFileSystem), dir, createWebpackData(files));
            } else {
              break;
            }
            count--;
          }
        };
      }
    };
    const afterResolversHook = () => {
      if (this._staticModules) {
        for (const [filePath, contents] of Object.entries(this._staticModules)) {
          this.writeModule(filePath, contents);
        }
        this._staticModules = null;
      }
    };

    const watchRunHook = (watcher, callback) => {
      this._watcher = watcher.compiler || watcher;
      const virtualFiles = (compiler as any).inputFileSystem._virtualFiles;
      const fts = compiler.fileTimestamps as any;
      if (virtualFiles && fts && typeof fts.set === 'function') {
        Object.keys(virtualFiles).forEach((file) => {
          fts.set(file, +virtualFiles[file].stats.mtime);
        });
      }
      callback();
    };

    if (compiler.hooks) {
      compiler.hooks.afterEnvironment.tap('VirtualModulesPlugin', afterEnvironmentHook);
      compiler.hooks.afterResolvers.tap('VirtualModulesPlugin', afterResolversHook);
      compiler.hooks.watchRun.tapAsync('VirtualModulesPlugin', watchRunHook);
    } else {
      (compiler as any).plugin('after-environment', afterEnvironmentHook);
      (compiler as any).plugin('after-resolvers', afterResolversHook);
      (compiler as any).plugin('watch-run', watchRunHook);
    }
  }
}

export = VirtualModulesPlugin;


code:
/**
 * Used to cache a stats object for the virtual file.
 * Extracted from the `mock-fs` package.
 *
 * @author Tim Schaub http://tschaub.net/
 * @author `webpack-virtual-modules` Contributors
 * @link https://github.com/tschaub/mock-fs/blob/master/lib/binding.js
 * @link https://github.com/tschaub/mock-fs/blob/master/license.md
 */
import constants from 'constants';

export class VirtualStats {
  /**
   * Create a new stats object.
   *
   * @param config Stats properties.
   */
  public constructor(config) {
    for (const key in config) {
      if (!Object.prototype.hasOwnProperty.call(config, key)) {
        continue;
      }
      this[key] = config[key];
    }
  }

  /**
   * Check if mode indicates property.
   */
  private _checkModeProperty(property): boolean {
    return ((this as any).mode & constants.S_IFMT) === property;
  }

  public isDirectory(): boolean {
    return this._checkModeProperty(constants.S_IFDIR);
  }

  public isFile(): boolean {
    return this._checkModeProperty(constants.S_IFREG);
  }

  public isBlockDevice(): boolean {
    return this._checkModeProperty(constants.S_IFBLK);
  }

  public isCharacterDevice(): boolean {
    return this._checkModeProperty(constants.S_IFCHR);
  }

  public isSymbolicLink(): boolean {
    return this._checkModeProperty(constants.S_IFLNK);
  }

  public isFIFO(): boolean {
    return this._checkModeProperty(constants.S_IFIFO);
  }

  public isSocket(): boolean {
    return this._checkModeProperty(constants.S_IFSOCK);
  }
}


code:
[![npm][npm]][npm-url]

[![node][node]][node-url]
[![builds2][builds2]][builds2-url]
[![coverage][cover]][cover-url]
[![licenses][licenses]][licenses-url]
[![PR's welcome][prs]][prs-url]

webpack

    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.

## Table of Contents

1. [Install](#install)
2. [Introduction](#introduction)
3. [Concepts](#concepts)
4. [Contributing](#contributing)
5. [Support](#support)
6. [Core Team](#core-team)
7. [Sponsoring](#sponsoring)
8. [Premium Partners](#premium-partners)
9. [Other Backers and Sponsors](#other-backers-and-sponsors)
10. [Gold Sponsors](#gold-sponsors)
11. [Silver Sponsors](#silver-sponsors)
12. [Bronze Sponsors](#bronze-sponsors)
13. [Backers](#backers)
14. [Special Thanks](#special-thanks-to)

Install

Install with npm:

```bash
npm install --save-dev webpack
```

Install with yarn:

```bash
yarn add webpack --dev
```

Introduction

Webpack is a bundler for modules. The main purpose is to bundle JavaScript
files for usage in a browser, yet it is also capable of transforming, bundling,
or packaging just about any resource or asset.

**TL;DR**

- Bundles [ES Modules](https://www.2ality.com/2014/09/es6-modules-final.html), [CommonJS](http://wiki.commonjs.org/), and [AMD](https://github.com/amdjs/amdjs-api/wiki/AMD) modules (even combined).
- Can create a single bundle or multiple chunks that are asynchronously loaded at runtime (to reduce initial loading time).
- Dependencies are resolved during compilation, reducing the runtime size.
- Loaders can preprocess files while compiling, e.g. TypeScript to JavaScript, Handlebars strings to compiled functions, images to Base64, etc.
- Highly modular plugin system to do whatever else your application requires.

### Get Started

Check out webpack's quick [**Get Started**](https://webpack.js.org/guides/getting-started) guide and the [other guides](https://webpack.js.org/guides/).

### Browser Compatibility

Webpack supports all browsers that are [ES5-compliant](https://kangax.github.io/compat-table/es5/) (IE8 and below are not supported).
Webpack also needs `Promise` for `import()` and `require.ensure()`. If you want to support older browsers, you will need to [load a polyfill](https://webpack.js.org/guides/shimming/) before using these expressions.

Concepts

### [Plugins](https://webpack.js.org/plugins/)

Webpack has a [rich plugin
interface](https://webpack.js.org/plugins/). Most of the features
within webpack itself use this plugin interface. This makes webpack very
**flexible**.

|                   Name                    |       Status       |    Install Size     | Description                                                                             |
| :---------------------------------------: | :----------------: | :-----------------: | :-------------------------------------------------------------------------------------- |
|    [mini-css-extract-plugin][mini-css]    |  ![mini-css-npm]   |  ![mini-css-size]   | Extracts CSS into separate files. It creates a CSS file per JS file which contains CSS. |
| [compression-webpack-plugin][compression] | ![compression-npm] | ![compression-size] | Prepares compressed versions of assets to serve them with Content-Encoding              |
|    [html-webpack-plugin][html-plugin]     | ![html-plugin-npm] | ![html-plugin-size] | Simplifies creation of HTML files (`index.html`) to serve your bundles                  |
|         [pug-plugin][pug-plugin]          | ![pug-plugin-npm]  | ![pug-plugin-size]  | Renders Pug files to HTML, extracts JS and CSS from sources specified directly in Pug.  |

[common-npm]: https://img.shields.io/npm/v/webpack.svg
[mini-css]: https://github.com/webpack-contrib/mini-css-extract-plugin
[mini-css-npm]: https://img.shields.io/npm/v/mini-css-extract-plugin.svg
[mini-css-size]: https://packagephobia.com/badge?p=mini-css-extract-plugin
[component]: https://github.com/webpack-contrib/component-webpack-plugin
[component-npm]: https://img.shields.io/npm/v/component-webpack-plugin.svg
[component-size]: https://packagephobia.com/badge?p=component-webpack-plugin
[compression]: https://github.com/webpack-contrib/compression-webpack-plugin
[compression-npm]: https://img.shields.io/npm/v/compression-webpack-plugin.svg
[compression-size]: https://packagephobia.com/badge?p=compression-webpack-plugin
[html-plugin]: https://github.com/jantimon/html-webpack-plugin
[html-plugin-npm]: https://img.shields.io/npm/v/html-webpack-plugin.svg
[html-plugin-size]: https://packagephobia.com/badge?p=html-webpack-plugin
[pug-plugin]: https://github.com/webdiscus/pug-plugin
[pug-plugin-npm]: https://img.shields.io/npm/v/pug-plugin.svg
[pug-plugin-size]: https://packagephobia.com/badge?p=pug-plugin

### [Loaders](https://webpack.js.org/loaders/)

Webpack enables the use of loaders to preprocess files. This allows you to bundle
**any static resource** way beyond JavaScript. You can easily [write your own
loaders](https://webpack.js.org/api/loaders/) using Node.js.

Loaders are activated by using `loadername!` prefixes in `require()` statements,
or are automatically applied via regex from your webpack configuration.

#### Files

|       Name        |   Status   | Install Size | Description                                              |
| :---------------: | :--------: | :----------: | :------------------------------------------------------- |
| [val-loader][val] | ![val-npm] | ![val-size]  | Executes code as module and considers exports as JS code |

[val]: https://github.com/webpack-contrib/val-loader
[val-npm]: https://img.shields.io/npm/v/val-loader.svg
[val-size]: https://packagephobia.com/badge?p=val-loader

#### JSON

|                                                                   Name                                                                    |   Status    | Install Size |           Description            |
| :---------------------------------------------------------------------------------------------------------------------------------------: | :---------: | :----------: | :------------------------------: |
|  | ![cson-npm] | ![cson-size] | Loads and transpiles a CSON file |

[cson-npm]: https://img.shields.io/npm/v/cson-loader.svg
[cson-size]: https://packagephobia.com/badge?p=cson-loader

#### Transpiling

|                                                                                Name                                                                                |    Status     |  Install Size  | Description                                                                                |
| :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :-----------: | :------------: | :------------------------------------------------------------------------------------------------ |
|                                                                                | ![babel-npm]  | ![babel-size]  | Loads ES2015+ code and transpiles to ES5 using Babel |
|  |  ![type-npm]  |  ![type-size]  | Loads TypeScript like JavaScript                                                                  |
|                                                                                | ![coffee-npm] | ![coffee-size] | Loads CoffeeScript like JavaScript                                                                |

[babel-npm]: https://img.shields.io/npm/v/babel-loader.svg
[babel-size]: https://packagephobia.com/badge?p=babel-loader
[coffee-npm]: https://img.shields.io/npm/v/coffee-loader.svg
[coffee-size]: https://packagephobia.com/badge?p=coffee-loader
[type-npm]: https://img.shields.io/npm/v/ts-loader.svg
[type-size]: https://packagephobia.com/badge?p=ts-loader

#### Templating

|                                                                                Name                                                                                |     Status      |   Install Size   | Description                                                                             |
| :-----------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :-------------: | :--------------: | :-------------------------------------------------------------------------------------- |
|                              |   ![html-npm]   |   ![html-size]   | Exports HTML as string, requires references to static resources                         |
|      |   ![pug-npm]    |   ![pug-size]    | Loads Pug templates and returns a function                                              |
|  |   ![pug3-npm]   |   ![pug3-size]   | Compiles Pug to a function or HTML string, useful for use with Vue, React, Angular      |
|                                |    ![md-npm]    |    ![md-size]    | Compiles Markdown to HTML                                                               |
|                                  | ![posthtml-npm] | ![posthtml-size] | Loads and transforms a HTML file using [PostHTML](https://github.com/posthtml/posthtml) |
|                          |   ![hbs-npm]    |   ![hbs-size]    | Compiles Handlebars to HTML                                                             |

[html-npm]: https://img.shields.io/npm/v/html-loader.svg
[html-size]: https://packagephobia.com/badge?p=html-loader
[pug-npm]: https://img.shields.io/npm/v/pug-loader.svg
[pug-size]: https://packagephobia.com/badge?p=pug-loader
[pug3-npm]: https://img.shields.io/npm/v/@webdiscus/pug-loader.svg
[pug3-size]: https://packagephobia.com/badge?p=@webdiscus/pug-loader
[jade-npm]: https://img.shields.io/npm/v/jade-loader.svg
[jade-size]: https://packagephobia.com/badge?p=jade-loader
[md-npm]: https://img.shields.io/npm/v/markdown-loader.svg
[md-size]: https://packagephobia.com/badge?p=markdown-loader
[posthtml-npm]: https://img.shields.io/npm/v/posthtml-loader.svg
[posthtml-size]: https://packagephobia.com/badge?p=posthtml-loader
[hbs-npm]: https://img.shields.io/npm/v/handlebars-loader.svg
[hbs-size]: https://packagephobia.com/badge?p=handlebars-loader

#### Styling

|                                                                     Name                                                                      |     Status     |  Install Size   | Description                                                              |
| :-------------------------------------------------------------------------------------------------------------------------------------------: | :------------: | :-------------: | :----------------------------------------------------------------------- |
|                                    `<style>`                                    |  ![style-npm]  |  ![style-size]  | Add exports of a module as style to DOM                                  |
|     |   ![css-npm]   |   ![css-size]   | Loads CSS file with resolved imports and returns CSS code                |
|  |  ![less-npm]   |  ![less-size]   | Loads and compiles a LESS file                                           |
|   |  ![sass-npm]   |  ![sass-size]   | Loads and compiles a Sass/SCSS file                                      |
|           | ![stylus-npm]  | ![stylus-size]  | Loads and compiles a Stylus file                                         |
|       | ![postcss-npm] | ![postcss-size] | Loads and transforms a CSS/SSS file using [PostCSS](https://postcss.org) |

[style-npm]: https://img.shields.io/npm/v/style-loader.svg
[style-size]: https://packagephobia.com/badge?p=style-loader
[css-npm]: https://img.shields.io/npm/v/css-loader.svg
[css-size]: https://packagephobia.com/badge?p=css-loader
[less-npm]: https://img.shields.io/npm/v/less-loader.svg
[less-size]: https://packagephobia.com/badge?p=less-loader
[sass-npm]: https://img.shields.io/npm/v/sass-loader.svg
[sass-size]: https://packagephobia.com/badge?p=sass-loader
[stylus-npm]: https://img.shields.io/npm/v/stylus-loader.svg
[stylus-size]: https://packagephobia.com/badge?p=stylus-loader
[postcss-npm]: https://img.shields.io/npm/v/postcss-loader.svg
[postcss-size]: https://packagephobia.com/badge?p=postcss-loader

#### Frameworks

|                                                                             Name                                                                             |     Status     |  Install Size   | Description                                                                                |
| :----------------------------------------------------------------------------------------------------------------------------------------------------------: | :------------: | :-------------: | :----------------------------------------------------------------------------------------------------- |
|                              |   ![vue-npm]   |   ![vue-size]   | Loads and compiles Vue Components                                                                      |
|      | ![polymer-npm] | ![polymer-size] | Process HTML & CSS with preprocessor of choice and `require()` Web Components like first-class modules |
|  | ![angular-npm] | ![angular-size] | Loads and compiles Angular 2 Components                                                                |
|                            |  ![riot-npm]   |  ![riot-size]   | Riot official webpack loader                                                                           |
|                     | ![svelte-npm]  | ![svelte-size]  | Official Svelte loader                                                                                |

[vue-npm]: https://img.shields.io/npm/v/vue-loader.svg
[vue-size]: https://packagephobia.com/badge?p=vue-loader
[polymer-npm]: https://img.shields.io/npm/v/polymer-webpack-loader.svg
[polymer-size]: https://packagephobia.com/badge?p=polymer-webpack-loader
[angular-npm]: https://img.shields.io/npm/v/angular2-template-loader.svg
[angular-size]: https://packagephobia.com/badge?p=angular2-template-loader
[riot-npm]: https://img.shields.io/npm/v/riot-tag-loader.svg
[riot-size]: https://packagephobia.com/badge?p=riot-tag-loader
[svelte-npm]: https://img.shields.io/npm/v/svelte-loader.svg
[svelte-size]: https://packagephobia.com/badge?p=svelte-loader

### Performance

Webpack uses async I/O and has multiple caching levels. This makes webpack fast
and incredibly **fast** on incremental compilations.

### Module Formats

Webpack supports ES2015+, CommonJS and AMD modules **out of the box**. It performs clever static
analysis on the AST of your code. It even has an evaluation engine to evaluate
simple expressions. This allows you to **support most existing libraries** out of the box.

### [Code Splitting](https://webpack.js.org/guides/code-splitting/)

Webpack allows you to split your codebase into multiple chunks. Chunks are
loaded asynchronously at runtime. This reduces the initial loading time.

### [Optimizations](https://webpack.js.org/guides/production-build/)

Webpack can do many optimizations to **reduce the output size of your
JavaScript** by deduplicating frequently used modules, minifying, and giving
you full control of what is loaded initially and what is loaded at runtime
through code splitting. It can also make your code chunks **cache
friendly** by using hashes.

Contributing

**We want contributing to webpack to be fun, enjoyable, and educational for anyone, and everyone.** We have a [vibrant ecosystem](https://medium.com/webpack/contributors-guide/home) that spans beyond this single repo. We welcome you to check out any of the repositories in [our organization](https://github.com/webpack) or [webpack-contrib organization](https://github.com/webpack-contrib) which houses all of our loaders and plugins.

Contributions go far beyond pull requests and commits. Although we love giving you the opportunity to put your stamp on webpack, we also are thrilled to receive a variety of other contributions including:

- [Documentation](https://github.com/webpack/webpack.js.org) updates, enhancements, designs, or bugfixes
- Spelling or grammar fixes
- README.md corrections or redesigns
- Adding unit, or functional tests
- Triaging GitHub issues -- especially determining whether an issue still persists or is reproducible.
- [Searching #webpack on twitter](https://twitter.com/search?q=webpack) and helping someone else who needs help
- Teaching others how to contribute to one of the many webpack's repos!
- [Blogging, speaking about, or creating tutorials](https://github.com/webpack-contrib/awesome-webpack) about one of webpack's many features.
- Helping others in our webpack [gitter channel](https://gitter.im/webpack/webpack).

To get started have a look at our [documentation on contributing](https://github.com/webpack/webpack/blob/main/CONTRIBUTING.md).

If you are worried or don't know where to start, you can **always** reach out to [Sean Larkin (@TheLarkInn) on Twitter](https://twitter.com/thelarkinn) or simply submit an issue and a maintainer can help give you guidance!

We have also started a series on our [Medium Publication](https://medium.com/webpack) called [The Contributor's Guide to webpack](https://medium.com/webpack/contributors-guide/home). We welcome you to read it and post any questions or responses if you still need help.

_Looking to speak about webpack?_ We'd **love** to review your talk abstract/CFP! You can email it to webpack [at] opencollective [dot] com and we can give pointers or tips!!!

Creating your own plugins and loaders

If you create a loader or plugin, we would <3 for you to open source it, and put it on npm. We follow the `x-loader`, `x-webpack-plugin` naming convention.

Support

We consider webpack to be a low-level tool used not only individually but also layered beneath other awesome tools. Because of its flexibility, webpack isn't always the _easiest_ entry-level solution, however we do believe it is the most powerful. That said, we're always looking for ways to improve and simplify the tool without compromising functionality. If you have any ideas on ways to accomplish this, we're all ears!

If you're just getting started, take a look at [our new docs and concepts page](https://webpack.js.org/concepts/). This has a high level overview that is great for beginners!!

Looking for webpack 1 docs? Please check out the old [wiki](https://github.com/webpack/docs/wiki/contents), but note that this deprecated version is no longer supported.

If you want to discuss something or just need help, [here is our Gitter room](https://gitter.im/webpack/webpack) where there are always individuals looking to help out!

If you are still having difficulty, we would love for you to post
a question to [StackOverflow with the webpack tag](https://stackoverflow.com/tags/webpack). It is much easier to answer questions that include your webpack.config.js and relevant files! So if you can provide them, we'd be extremely grateful (and more likely to help you find the answer!)

If you are twitter savvy you can tweet #webpack with your question and someone should be able to reach out and help also.

If you have discovered a 🐜 or have a feature suggestion, feel free to create an issue on GitHub.

### License

[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fwebpack%2Fwebpack.svg?type=large)](https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fwebpack%2Fwebpack?ref=badge_large)

Core Team

        Tobias Koppers

Core

Founder of webpack

        Johannes Ewald

Loaders & Plugins

Early adopter of webpack

        Sean T. Larkin

Public Relations

Founder of the core team

        Kees Kluskens

Development

Sponsor

Sponsoring

Most of the core team members, webpack contributors and contributors in the ecosystem do this open source work in their free time. If you use webpack for a serious task, and you'd like us to invest more time on it, please donate. This project increases your income/productivity too. It makes development and applications faster and it reduces the required bandwidth.

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

Premium Partners

Other Backers and Sponsors

Before we started using OpenCollective, donations were made anonymously. Now that we have made the switch, we would like to acknowledge these sponsors (and the ones who continue to donate using OpenCollective). If we've missed someone, please send us a PR, and we'll add you to this list.

Gold Sponsors

[Become a gold sponsor](https://opencollective.com/webpack#sponsor) and get your logo on our README on GitHub with a link to your site.

Silver Sponsors

[Become a silver sponsor](https://opencollective.com/webpack#sponsor) and get your logo on our README on GitHub with a link to your site.

Bronze Sponsors

[Become a bronze sponsor](https://opencollective.com/webpack#sponsor) and get your logo on our README on GitHub with a link to your site.

Backers

[Become a backer](https://opencollective.com/webpack#backer) and get your image on our README on GitHub with a link to your site.

Special Thanks to

(In chronological order)

- [@google](https://github.com/google) for [Google Web Toolkit (GWT)](http://www.gwtproject.org/), which aims to compile Java to JavaScript. It features a similar [Code Splitting](http://www.gwtproject.org/doc/latest/DevGuideCodeSplitting.html) as webpack.
- [@medikoo](https://github.com/medikoo) for [modules-webmake](https://github.com/medikoo/modules-webmake), which is a similar project. webpack was born because I wanted Code Splitting for modules-webmake. Interestingly the [Code Splitting issue is still open](https://github.com/medikoo/modules-webmake/issues/7) (thanks also to @Phoscur for the discussion).
- [@substack](https://github.com/substack) for [browserify](https://browserify.org/), which is a similar project and source for many ideas.
- [@jrburke](https://github.com/jrburke) for [require.js](https://requirejs.org/), which is a similar project and source for many ideas.
- [@defunctzombie](https://github.com/defunctzombie) for the [browser-field spec](https://github.com/defunctzombie/package-browser-field-spec), which makes modules available for node.js, browserify and webpack.
- Every early webpack user, which contributed to webpack by writing issues or PRs. You influenced the direction...
- [@shama](https://github.com/shama), [@jhnns](https://github.com/jhnns) and [@sokra](https://github.com/sokra) for maintaining this project
- Everyone who has written a loader for webpack. You are the ecosystem...
- Everyone I forgot to mention here, but also influenced webpack.

[npm]: https://img.shields.io/npm/v/webpack.svg
[npm-url]: https://npmjs.com/package/webpack
[node]: https://img.shields.io/node/v/webpack.svg
[node-url]: https://nodejs.org
[prs]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg
[prs-url]: https://webpack.js.org/contribute/
[builds2]: https://dev.azure.com/webpack/webpack/_apis/build/status/webpack.webpack
[builds2-url]: https://dev.azure.com/webpack/webpack/_build/latest?definitionId=3
[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://codecov.io/gh/webpack/webpack/branch/master/graph/badge.svg?token=mDP3mQJNnn
[cover-url]: https://codecov.io/gh/webpack/webpack


code:
# Reporting Security Issues

If you discover a security issue in webpack, please report it by sending an
email to [webpack@opencollective.com](mailto:webpack@opencollective.com).

This will allow us to assess the risk, and make a fix available before we add a
bug report to the GitHub repository.

Thanks for helping make webpack safe for everyone.


code:
#!/usr/bin/env node

/**
 * @param {string} command process to run
 * @param {string[]} args command line arguments
 * @returns {Promise<void>} promise
 */
const runCommand = (command, args) => {
	const cp = require("child_process");
	return new Promise((resolve, reject) => {
		const executedCommand = cp.spawn(command, args, {
			stdio: "inherit",
			shell: true
		});

		executedCommand.on("error", error => {
			reject(error);
		});

		executedCommand.on("exit", code => {
			if (code === 0) {
				resolve();
			} else {
				reject();
			}
		});
	});
};

/**
 * @param {string} packageName name of the package
 * @returns {boolean} is the package installed?
 */
const isInstalled = packageName => {
	if (process.versions.pnp) {
		return true;
	}

	const path = require("path");
	const fs = require("graceful-fs");

	let dir = __dirname;

	do {
		try {
			if (
				fs.statSync(path.join(dir, "node_modules", packageName)).isDirectory()
			) {
				return true;
			}
		} catch (_error) {
			// Nothing
		}
	} while (dir !== (dir = path.dirname(dir)));

	// https://github.com/nodejs/node/blob/v18.9.1/lib/internal/modules/cjs/loader.js#L1274
	// eslint-disable-next-line no-warning-comments
	// @ts-ignore
	for (const internalPath of require("module").globalPaths) {
		try {
			if (fs.statSync(path.join(internalPath, packageName)).isDirectory()) {
				return true;
			}
		} catch (_error) {
			// Nothing
		}
	}

	return false;
};

/**
 * @param {CliOption} cli options
 * @returns {void}
 */
const runCli = cli => {
	const path = require("path");
	const pkgPath = require.resolve(`${cli.package}/package.json`);
	const pkg = require(pkgPath);

	if (pkg.type === "module" || /\.mjs/i.test(pkg.bin[cli.binName])) {
		import(path.resolve(path.dirname(pkgPath), pkg.bin[cli.binName])).catch(
			error => {
				console.error(error);
				process.exitCode = 1;
			}
		);
	} else {
		require(path.resolve(path.dirname(pkgPath), pkg.bin[cli.binName]));
	}
};

/**
 * @typedef {object} CliOption
 * @property {string} name display name
 * @property {string} package npm package name
 * @property {string} binName name of the executable file
 * @property {boolean} installed currently installed?
 * @property {string} url homepage
 */

/** @type {CliOption} */
const cli = {
	name: "webpack-cli",
	package: "webpack-cli",
	binName: "webpack-cli",
	installed: isInstalled("webpack-cli"),
	url: "https://github.com/webpack/webpack-cli"
};

if (!cli.installed) {
	const path = require("path");
	const fs = require("graceful-fs");
	const readLine = require("readline");

	const notify =
		"CLI for webpack must be installed.\n" + `  ${cli.name} (${cli.url})\n`;

	console.error(notify);

	/** @type {string | undefined} */
	let packageManager;

	if (fs.existsSync(path.resolve(process.cwd(), "yarn.lock"))) {
		packageManager = "yarn";
	} else if (fs.existsSync(path.resolve(process.cwd(), "pnpm-lock.yaml"))) {
		packageManager = "pnpm";
	} else {
		packageManager = "npm";
	}

	const installOptions = [packageManager === "yarn" ? "add" : "install", "-D"];

	console.error(
		`We will use "${packageManager}" to install the CLI via "${packageManager} ${installOptions.join(
			" "
		)} ${cli.package}".`
	);

	const question = `Do you want to install 'webpack-cli' (yes/no): `;

	const questionInterface = readLine.createInterface({
		input: process.stdin,
		output: process.stderr
	});

	// In certain scenarios (e.g. when STDIN is not in terminal mode), the callback function will not be
	// executed. Setting the exit code here to ensure the script exits correctly in those cases. The callback
	// function is responsible for clearing the exit code if the user wishes to install webpack-cli.
	process.exitCode = 1;
	questionInterface.question(question, answer => {
		questionInterface.close();

		const normalizedAnswer = answer.toLowerCase().startsWith("y");

		if (!normalizedAnswer) {
			console.error(
				"You need to install 'webpack-cli' to use webpack via CLI.\n" +
					"You can also install the CLI manually."
			);

			return;
		}
		process.exitCode = 0;

		console.log(
			`Installing '${
				cli.package
			}' (running '${packageManager} ${installOptions.join(" ")} ${
				cli.package
			}')...`
		);

		runCommand(
			/** @type {string} */ (packageManager),
			installOptions.concat(cli.package)
		)
			.then(() => {
				runCli(cli);
			})
			.catch(error => {
				console.error(error);
				process.exitCode = 1;
			});
	});
} else {
	runCli(cli);
}


code:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
/* globals __webpack_hash__ */
if (module.hot) {
	/** @type {undefined|string} */
	var lastHash;
	var upToDate = function upToDate() {
		return /** @type {string} */ (lastHash).indexOf(__webpack_hash__) >= 0;
	};
	var log = require("./log");
	var check = function check() {
		module.hot
			.check(true)
			.then(function (updatedModules) {
				if (!updatedModules) {
					log(
						"warning",
						"[HMR] Cannot find update. " +
							(typeof window !== "undefined"
								? "Need to do a full reload!"
								: "Please reload manually!")
					);
					log(
						"warning",
						"[HMR] (Probably because of restarting the webpack-dev-server)"
					);
					if (typeof window !== "undefined") {
						window.location.reload();
					}
					return;
				}

				if (!upToDate()) {
					check();
				}

				require("./log-apply-result")(updatedModules, updatedModules);

				if (upToDate()) {
					log("info", "[HMR] App is up to date.");
				}
			})
			.catch(function (err) {
				var status = module.hot.status();
				if (["abort", "fail"].indexOf(status) >= 0) {
					log(
						"warning",
						"[HMR] Cannot apply update. " +
							(typeof window !== "undefined"
								? "Need to do a full reload!"
								: "Please reload manually!")
					);
					log("warning", "[HMR] " + log.formatError(err));
					if (typeof window !== "undefined") {
						window.location.reload();
					}
				} else {
					log("warning", "[HMR] Update failed: " + log.formatError(err));
				}
			});
	};
	var hotEmitter = require("./emitter");
	hotEmitter.on("webpackHotUpdate", function (currentHash) {
		lastHash = currentHash;
		if (!upToDate() && module.hot.status() === "idle") {
			log("info", "[HMR] Checking for updates on the server...");
			check();
		}
	});
	log("info", "[HMR] Waiting for update signal from WDS...");
} else {
	throw new Error("[HMR] Hot Module Replacement is disabled.");
}


code:
var EventEmitter = require("events");
module.exports = new EventEmitter();


code:
/* global __resourceQuery */

"use strict";

var urlBase = decodeURIComponent(__resourceQuery.slice(1));

/**
 * @param {{ data: string, onError: (err: Error) => void, active: boolean, module: module }} options options
 * @returns {() => void} function to destroy response
 */
exports.keepAlive = function (options) {
	var data = options.data;
	var onError = options.onError;
	var active = options.active;
	var module = options.module;
	/** @type {import("http").IncomingMessage} */
	var response;
	var request = (
		urlBase.startsWith("https") ? require("https") : require("http")
	).request(
		urlBase + data,
		{
			agent: false,
			headers: { accept: "text/event-stream" }
		},
		function (res) {
			response = res;
			response.on("error", errorHandler);
			if (!active && !module.hot) {
				console.log(
					"Hot Module Replacement is not enabled. Waiting for process restart..."
				);
			}
		}
	);

	/**
	 * @param {Error} err error
	 */
	function errorHandler(err) {
		err.message =
			"Problem communicating active modules to the server: " + err.message;
		onError(err);
	}
	request.on("error", errorHandler);
	request.end();
	return function () {
		response.destroy();
	};
};


code:
/* global __resourceQuery */

"use strict";

if (typeof EventSource !== "function") {
	throw new Error(
		"Environment doesn't support lazy compilation (requires EventSource)"
	);
}

var urlBase = decodeURIComponent(__resourceQuery.slice(1));
/** @type {EventSource | undefined} */
var activeEventSource;
var activeKeys = new Map();
var errorHandlers = new Set();

var updateEventSource = function updateEventSource() {
	if (activeEventSource) activeEventSource.close();
	if (activeKeys.size) {
		activeEventSource = new EventSource(
			urlBase + Array.from(activeKeys.keys()).join("@")
		);
		/**
		 * @this {EventSource}
		 * @param {Event & { message?: string, filename?: string, lineno?: number, colno?: number, error?: Error }} event event
		 */
		activeEventSource.onerror = function (event) {
			errorHandlers.forEach(function (onError) {
				onError(
					new Error(
						"Problem communicating active modules to the server: " +
							event.message +
							" " +
							event.filename +
							":" +
							event.lineno +
							":" +
							event.colno +
							" " +
							event.error
					)
				);
			});
		};
	} else {
		activeEventSource = undefined;
	}
};

/**
 * @param {{ data: string, onError: (err: Error) => void, active: boolean, module: module }} options options
 * @returns {() => void} function to destroy response
 */
exports.keepAlive = function (options) {
	var data = options.data;
	var onError = options.onError;
	var active = options.active;
	var module = options.module;
	errorHandlers.add(onError);
	var value = activeKeys.get(data) || 0;
	activeKeys.set(data, value + 1);
	if (value === 0) {
		updateEventSource();
	}
	if (!active && !module.hot) {
		console.log(
			"Hot Module Replacement is not enabled. Waiting for process restart..."
		);
	}

	return function () {
		errorHandlers.delete(onError);
		setTimeout(function () {
			var value = activeKeys.get(data);
			if (value === 1) {
				activeKeys.delete(data);
				updateEventSource();
			} else {
				activeKeys.set(data, value - 1);
			}
		}, 1000);
	};
};


code:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

/**
 * @param {(string | number)[]} updatedModules updated modules
 * @param {(string | number)[] | null} renewedModules renewed modules
 */
module.exports = function (updatedModules, renewedModules) {
	var unacceptedModules = updatedModules.filter(function (moduleId) {
		return renewedModules && renewedModules.indexOf(moduleId) < 0;
	});
	var log = require("./log");

	if (unacceptedModules.length > 0) {
		log(
			"warning",
			"[HMR] The following modules couldn't be hot updated: (They would need a full reload!)"
		);
		unacceptedModules.forEach(function (moduleId) {
			log("warning", "[HMR]  - " + moduleId);
		});
	}

	if (!renewedModules || renewedModules.length === 0) {
		log("info", "[HMR] Nothing hot updated.");
	} else {
		log("info", "[HMR] Updated modules:");
		renewedModules.forEach(function (moduleId) {
			if (typeof moduleId === "string" && moduleId.indexOf("!") !== -1) {
				var parts = moduleId.split("!");
				log.groupCollapsed("info", "[HMR]  - " + parts.pop());
				log("info", "[HMR]  - " + moduleId);
				log.groupEnd("info");
			} else {
				log("info", "[HMR]  - " + moduleId);
			}
		});
		var numberIds = renewedModules.every(function (moduleId) {
			return typeof moduleId === "number";
		});
		if (numberIds)
			log(
				"info",
				'[HMR] Consider using the optimization.moduleIds: "named" for module names.'
			);
	}
};


code:
/** @typedef {"info" | "warning" | "error"} LogLevel */

/** @type {LogLevel} */
var logLevel = "info";

function dummy() {}

/**
 * @param {LogLevel} level log level
 * @returns {boolean} true, if should log
 */
function shouldLog(level) {
	var shouldLog =
		(logLevel === "info" && level === "info") ||
		(["info", "warning"].indexOf(logLevel) >= 0 && level === "warning") ||
		(["info", "warning", "error"].indexOf(logLevel) >= 0 && level === "error");
	return shouldLog;
}

/**
 * @param {(msg?: string) => void} logFn log function
 * @returns {(level: LogLevel, msg?: string) => void} function that logs when log level is sufficient
 */
function logGroup(logFn) {
	return function (level, msg) {
		if (shouldLog(level)) {
			logFn(msg);
		}
	};
}

/**
 * @param {LogLevel} level log level
 * @param {string|Error} msg message
 */
module.exports = function (level, msg) {
	if (shouldLog(level)) {
		if (level === "info") {
			console.log(msg);
		} else if (level === "warning") {
			console.warn(msg);
		} else if (level === "error") {
			console.error(msg);
		}
	}
};

var group = console.group || dummy;
var groupCollapsed = console.groupCollapsed || dummy;
var groupEnd = console.groupEnd || dummy;

module.exports.group = logGroup(group);

module.exports.groupCollapsed = logGroup(groupCollapsed);

module.exports.groupEnd = logGroup(groupEnd);

/**
 * @param {LogLevel} level log level
 */
module.exports.setLogLevel = function (level) {
	logLevel = level;
};

/**
 * @param {Error} err error
 * @returns {string} formatted error
 */
module.exports.formatError = function (err) {
	var message = err.message;
	var stack = err.stack;
	if (!stack) {
		return message;
	} else if (stack.indexOf(message) < 0) {
		return message + "\n" + stack;
	} else {
		return stack;
	}
};


code:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
/*globals __webpack_hash__ */
if (module.hot) {
	/** @type {undefined|string} */
	var lastHash;
	var upToDate = function upToDate() {
		return /** @type {string} */ (lastHash).indexOf(__webpack_hash__) >= 0;
	};
	var log = require("./log");
	var check = function check() {
		module.hot
			.check()
			.then(function (updatedModules) {
				if (!updatedModules) {
					log("warning", "[HMR] Cannot find update. Need to do a full reload!");
					log(
						"warning",
						"[HMR] (Probably because of restarting the webpack-dev-server)"
					);
					return;
				}

				return module.hot
					.apply({
						ignoreUnaccepted: true,
						ignoreDeclined: true,
						ignoreErrored: true,
						onUnaccepted: function (data) {
							log(
								"warning",
								"Ignored an update to unaccepted module " +
									data.chain.join(" -> ")
							);
						},
						onDeclined: function (data) {
							log(
								"warning",
								"Ignored an update to declined module " +
									data.chain.join(" -> ")
							);
						},
						onErrored: function (data) {
							log("error", data.error);
							log(
								"warning",
								"Ignored an error while updating module " +
									data.moduleId +
									" (" +
									data.type +
									")"
							);
						}
					})
					.then(function (renewedModules) {
						if (!upToDate()) {
							check();
						}

						require("./log-apply-result")(updatedModules, renewedModules);

						if (upToDate()) {
							log("info", "[HMR] App is up to date.");
						}
					});
			})
			.catch(function (err) {
				var status = module.hot.status();
				if (["abort", "fail"].indexOf(status) >= 0) {
					log(
						"warning",
						"[HMR] Cannot check for update. Need to do a full reload!"
					);
					log("warning", "[HMR] " + log.formatError(err));
				} else {
					log("warning", "[HMR] Update check failed: " + log.formatError(err));
				}
			});
	};
	var hotEmitter = require("./emitter");
	hotEmitter.on("webpackHotUpdate", function (currentHash) {
		lastHash = currentHash;
		if (!upToDate()) {
			var status = module.hot.status();
			if (status === "idle") {
				log("info", "[HMR] Checking for updates on the server...");
				check();
			} else if (["abort", "fail"].indexOf(status) >= 0) {
				log(
					"warning",
					"[HMR] Cannot apply update as a previous update " +
						status +
						"ed. Need to do a full reload!"
				);
			}
		}
	});
	log("info", "[HMR] Waiting for update signal from WDS...");
} else {
	throw new Error("[HMR] Hot Module Replacement is disabled.");
}


code:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
/*globals __resourceQuery */
if (module.hot) {
	var hotPollInterval = +__resourceQuery.slice(1) || 10 * 60 * 1000;
	var log = require("./log");

	/**
	 * @param {boolean=} fromUpdate true when called from update
	 */
	var checkForUpdate = function checkForUpdate(fromUpdate) {
		if (module.hot.status() === "idle") {
			module.hot
				.check(true)
				.then(function (updatedModules) {
					if (!updatedModules) {
						if (fromUpdate) log("info", "[HMR] Update applied.");
						return;
					}
					require("./log-apply-result")(updatedModules, updatedModules);
					checkForUpdate(true);
				})
				.catch(function (err) {
					var status = module.hot.status();
					if (["abort", "fail"].indexOf(status) >= 0) {
						log("warning", "[HMR] Cannot apply update.");
						log("warning", "[HMR] " + log.formatError(err));
						log("warning", "[HMR] You need to restart the application!");
					} else {
						log("warning", "[HMR] Update failed: " + log.formatError(err));
					}
				});
		}
	};
	setInterval(checkForUpdate, hotPollInterval);
} else {
	throw new Error("[HMR] Hot Module Replacement is disabled.");
}


code:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
/*globals __resourceQuery */
if (module.hot) {
	var log = require("./log");

	/**
	 * @param {boolean=} fromUpdate true when called from update
	 */
	var checkForUpdate = function checkForUpdate(fromUpdate) {
		module.hot
			.check()
			.then(function (updatedModules) {
				if (!updatedModules) {
					if (fromUpdate) log("info", "[HMR] Update applied.");
					else log("warning", "[HMR] Cannot find update.");
					return;
				}

				return module.hot
					.apply({
						ignoreUnaccepted: true,
						onUnaccepted: function (data) {
							log(
								"warning",
								"Ignored an update to unaccepted module " +
									data.chain.join(" -> ")
							);
						}
					})
					.then(function (renewedModules) {
						require("./log-apply-result")(updatedModules, renewedModules);

						checkForUpdate(true);
						return null;
					});
			})
			.catch(function (err) {
				var status = module.hot.status();
				if (["abort", "fail"].indexOf(status) >= 0) {
					log("warning", "[HMR] Cannot apply update.");
					log("warning", "[HMR] " + log.formatError(err));
					log("warning", "[HMR] You need to restart the application!");
				} else {
					log("warning", "[HMR] Update failed: " + (err.stack || err.message));
				}
			});
	};

	process.on(__resourceQuery.slice(1) || "SIGUSR2", function () {
		if (module.hot.status() !== "idle") {
			log(
				"warning",
				"[HMR] Got signal but currently in " + module.hot.status() + " state."
			);
			log("warning", "[HMR] Need to be in idle state to start hot update.");
			return;
		}

		checkForUpdate();
	});
} else {
	throw new Error("[HMR] Hot Module Replacement is disabled.");
}