progress on migrating to heex templates and font-icons

This commit is contained in:
Adam Piontek 2022-08-13 07:32:36 -04:00
commit 3eff955672
21793 changed files with 2161968 additions and 16895 deletions
assets_old/node_modules/webpack/lib
APIPlugin.jsAbstractMethodError.jsAsyncDependenciesBlock.jsAsyncDependencyToInitialChunkError.jsAutomaticPrefetchPlugin.jsBannerPlugin.jsCache.jsCacheFacade.jsCaseSensitiveModulesWarning.jsChunk.jsChunkGraph.jsChunkGroup.jsChunkRenderError.jsChunkTemplate.jsCleanPlugin.jsCodeGenerationError.jsCodeGenerationResults.jsCommentCompilationWarning.jsCompatibilityPlugin.jsCompilation.jsCompiler.jsConcatenationScope.jsConcurrentCompilationError.jsConditionalInitFragment.jsConstPlugin.jsContextExclusionPlugin.jsContextModule.jsContextModuleFactory.jsContextReplacementPlugin.jsDefinePlugin.jsDelegatedModule.jsDelegatedModuleFactoryPlugin.jsDelegatedPlugin.jsDependenciesBlock.jsDependency.jsDependencyTemplate.jsDependencyTemplates.jsDllEntryPlugin.jsDllModule.jsDllModuleFactory.jsDllPlugin.jsDllReferencePlugin.jsDynamicEntryPlugin.jsEntryOptionPlugin.jsEntryPlugin.jsEntrypoint.jsEnvironmentPlugin.jsErrorHelpers.jsEvalDevToolModulePlugin.jsEvalSourceMapDevToolPlugin.jsExportsInfo.jsExportsInfoApiPlugin.jsExternalModule.jsExternalModuleFactoryPlugin.jsExternalsPlugin.jsFileSystemInfo.jsFlagAllModulesAsUsedPlugin.jsFlagDependencyExportsPlugin.jsFlagDependencyUsagePlugin.jsFlagEntryExportAsUsedPlugin.jsGenerator.jsGraphHelpers.jsHarmonyLinkingError.jsHookWebpackError.jsHotModuleReplacementPlugin.jsHotUpdateChunk.jsIgnoreErrorModuleFactory.jsIgnorePlugin.jsIgnoreWarningsPlugin.jsInitFragment.jsInvalidDependenciesModuleWarning.jsJavascriptMetaInfoPlugin.jsLibManifestPlugin.jsLibraryTemplatePlugin.jsLoaderOptionsPlugin.jsLoaderTargetPlugin.jsMainTemplate.jsModule.jsModuleBuildError.jsModuleDependencyError.jsModuleDependencyWarning.jsModuleError.jsModuleFactory.jsModuleFilenameHelpers.jsModuleGraph.jsModuleGraphConnection.jsModuleInfoHeaderPlugin.jsModuleNotFoundError.jsModuleParseError.jsModuleProfile.jsModuleRestoreError.jsModuleStoreError.jsModuleTemplate.jsModuleWarning.jsMultiCompiler.jsMultiStats.jsMultiWatching.jsNoEmitOnErrorsPlugin.jsNoModeWarning.jsNodeStuffPlugin.js

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

@ -0,0 +1,220 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const RuntimeGlobals = require("./RuntimeGlobals");
const WebpackError = require("./WebpackError");
const ConstDependency = require("./dependencies/ConstDependency");
const BasicEvaluatedExpression = require("./javascript/BasicEvaluatedExpression");
const {
toConstantDependency,
evaluateToString
} = require("./javascript/JavascriptParserHelpers");
const ChunkNameRuntimeModule = require("./runtime/ChunkNameRuntimeModule");
const GetFullHashRuntimeModule = require("./runtime/GetFullHashRuntimeModule");
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
/* eslint-disable camelcase */
const REPLACEMENTS = {
__webpack_require__: {
expr: RuntimeGlobals.require,
req: [RuntimeGlobals.require],
type: "function",
assign: false
},
__webpack_public_path__: {
expr: RuntimeGlobals.publicPath,
req: [RuntimeGlobals.publicPath],
type: "string",
assign: true
},
__webpack_base_uri__: {
expr: RuntimeGlobals.baseURI,
req: [RuntimeGlobals.baseURI],
type: "string",
assign: true
},
__webpack_modules__: {
expr: RuntimeGlobals.moduleFactories,
req: [RuntimeGlobals.moduleFactories],
type: "object",
assign: false
},
__webpack_chunk_load__: {
expr: RuntimeGlobals.ensureChunk,
req: [RuntimeGlobals.ensureChunk],
type: "function",
assign: true
},
__non_webpack_require__: {
expr: "require",
req: null,
type: undefined, // type is not known, depends on environment
assign: true
},
__webpack_nonce__: {
expr: RuntimeGlobals.scriptNonce,
req: [RuntimeGlobals.scriptNonce],
type: "string",
assign: true
},
__webpack_hash__: {
expr: `${RuntimeGlobals.getFullHash}()`,
req: [RuntimeGlobals.getFullHash],
type: "string",
assign: false
},
__webpack_chunkname__: {
expr: RuntimeGlobals.chunkName,
req: [RuntimeGlobals.chunkName],
type: "string",
assign: false
},
__webpack_get_script_filename__: {
expr: RuntimeGlobals.getChunkScriptFilename,
req: [RuntimeGlobals.getChunkScriptFilename],
type: "function",
assign: true
},
__webpack_runtime_id__: {
expr: RuntimeGlobals.runtimeId,
req: [RuntimeGlobals.runtimeId],
assign: false
},
"require.onError": {
expr: RuntimeGlobals.uncaughtErrorHandler,
req: [RuntimeGlobals.uncaughtErrorHandler],
type: undefined, // type is not known, could be function or undefined
assign: true // is never a pattern
},
__system_context__: {
expr: RuntimeGlobals.systemContext,
req: [RuntimeGlobals.systemContext],
type: "object",
assign: false
},
__webpack_share_scopes__: {
expr: RuntimeGlobals.shareScopeMap,
req: [RuntimeGlobals.shareScopeMap],
type: "object",
assign: false
},
__webpack_init_sharing__: {
expr: RuntimeGlobals.initializeSharing,
req: [RuntimeGlobals.initializeSharing],
type: "function",
assign: true
}
};
/* eslint-enable camelcase */
class APIPlugin {
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(
"APIPlugin",
(compilation, { normalModuleFactory }) => {
compilation.dependencyTemplates.set(
ConstDependency,
new ConstDependency.Template()
);
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.chunkName)
.tap("APIPlugin", chunk => {
compilation.addRuntimeModule(
chunk,
new ChunkNameRuntimeModule(chunk.name)
);
return true;
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.getFullHash)
.tap("APIPlugin", (chunk, set) => {
compilation.addRuntimeModule(chunk, new GetFullHashRuntimeModule());
return true;
});
/**
* @param {JavascriptParser} parser the parser
*/
const handler = parser => {
Object.keys(REPLACEMENTS).forEach(key => {
const info = REPLACEMENTS[key];
parser.hooks.expression
.for(key)
.tap(
"APIPlugin",
toConstantDependency(parser, info.expr, info.req)
);
if (info.assign === false) {
parser.hooks.assign.for(key).tap("APIPlugin", expr => {
const err = new WebpackError(`${key} must not be assigned`);
err.loc = expr.loc;
throw err;
});
}
if (info.type) {
parser.hooks.evaluateTypeof
.for(key)
.tap("APIPlugin", evaluateToString(info.type));
}
});
parser.hooks.expression
.for("__webpack_layer__")
.tap("APIPlugin", expr => {
const dep = new ConstDependency(
JSON.stringify(parser.state.module.layer),
expr.range
);
dep.loc = expr.loc;
parser.state.module.addPresentationalDependency(dep);
return true;
});
parser.hooks.evaluateIdentifier
.for("__webpack_layer__")
.tap("APIPlugin", expr =>
(parser.state.module.layer === null
? new BasicEvaluatedExpression().setNull()
: new BasicEvaluatedExpression().setString(
parser.state.module.layer
)
).setRange(expr.range)
);
parser.hooks.evaluateTypeof
.for("__webpack_layer__")
.tap("APIPlugin", expr =>
new BasicEvaluatedExpression()
.setString(
parser.state.module.layer === null ? "object" : "string"
)
.setRange(expr.range)
);
};
normalModuleFactory.hooks.parser
.for("javascript/auto")
.tap("APIPlugin", handler);
normalModuleFactory.hooks.parser
.for("javascript/dynamic")
.tap("APIPlugin", handler);
normalModuleFactory.hooks.parser
.for("javascript/esm")
.tap("APIPlugin", handler);
}
);
}
}
module.exports = APIPlugin;

View file

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

View file

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

View file

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

View file

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

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

@ -0,0 +1,113 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { validate } = require("schema-utils");
const { ConcatSource } = require("webpack-sources");
const Compilation = require("./Compilation");
const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
const Template = require("./Template");
const schema = require("../schemas/plugins/BannerPlugin.json");
/** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginArgument} BannerPluginArgument */
/** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginOptions} BannerPluginOptions */
/** @typedef {import("./Compiler")} Compiler */
const wrapComment = str => {
if (!str.includes("\n")) {
return Template.toComment(str);
}
return `/*!\n * ${str
.replace(/\*\//g, "* /")
.split("\n")
.join("\n * ")
.replace(/\s+\n/g, "\n")
.trimRight()}\n */`;
};
class BannerPlugin {
/**
* @param {BannerPluginArgument} options options object
*/
constructor(options) {
if (typeof options === "string" || typeof options === "function") {
options = {
banner: options
};
}
validate(schema, options, {
name: "Banner Plugin",
baseDataPath: "options"
});
this.options = options;
const bannerOption = options.banner;
if (typeof bannerOption === "function") {
const getBanner = bannerOption;
this.banner = this.options.raw
? getBanner
: data => wrapComment(getBanner(data));
} else {
const banner = this.options.raw
? bannerOption
: wrapComment(bannerOption);
this.banner = () => banner;
}
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
const options = this.options;
const banner = this.banner;
const matchObject = ModuleFilenameHelpers.matchObject.bind(
undefined,
options
);
compiler.hooks.compilation.tap("BannerPlugin", compilation => {
compilation.hooks.processAssets.tap(
{
name: "BannerPlugin",
stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONS
},
() => {
for (const chunk of compilation.chunks) {
if (options.entryOnly && !chunk.canBeInitial()) {
continue;
}
for (const file of chunk.files) {
if (!matchObject(file)) {
continue;
}
const data = {
chunk,
filename: file
};
const comment = compilation.getPath(banner, data);
compilation.updateAsset(
file,
old => new ConcatSource(comment, "\n", old)
);
}
}
}
);
});
}
}
module.exports = BannerPlugin;

161
assets_old/node_modules/webpack/lib/Cache.js generated vendored Normal file
View file

@ -0,0 +1,161 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { AsyncParallelHook, AsyncSeriesBailHook, SyncHook } = require("tapable");
const {
makeWebpackError,
makeWebpackErrorCallback
} = require("./HookWebpackError");
/** @typedef {import("./WebpackError")} WebpackError */
/**
* @typedef {Object} Etag
* @property {function(): string} toString
*/
/**
* @template T
* @callback CallbackCache
* @param {WebpackError=} err
* @param {T=} result
* @returns {void}
*/
/**
* @callback GotHandler
* @param {any} result
* @param {function(Error=): void} callback
* @returns {void}
*/
const needCalls = (times, callback) => {
return err => {
if (--times === 0) {
return callback(err);
}
if (err && times > 0) {
times = 0;
return callback(err);
}
};
};
class Cache {
constructor() {
this.hooks = {
/** @type {AsyncSeriesBailHook<[string, Etag | null, GotHandler[]], any>} */
get: new AsyncSeriesBailHook(["identifier", "etag", "gotHandlers"]),
/** @type {AsyncParallelHook<[string, Etag | null, any]>} */
store: new AsyncParallelHook(["identifier", "etag", "data"]),
/** @type {AsyncParallelHook<[Iterable<string>]>} */
storeBuildDependencies: new AsyncParallelHook(["dependencies"]),
/** @type {SyncHook<[]>} */
beginIdle: new SyncHook([]),
/** @type {AsyncParallelHook<[]>} */
endIdle: new AsyncParallelHook([]),
/** @type {AsyncParallelHook<[]>} */
shutdown: new AsyncParallelHook([])
};
}
/**
* @template T
* @param {string} identifier the cache identifier
* @param {Etag | null} etag the etag
* @param {CallbackCache<T>} callback signals when the value is retrieved
* @returns {void}
*/
get(identifier, etag, callback) {
const gotHandlers = [];
this.hooks.get.callAsync(identifier, etag, gotHandlers, (err, result) => {
if (err) {
callback(makeWebpackError(err, "Cache.hooks.get"));
return;
}
if (result === null) {
result = undefined;
}
if (gotHandlers.length > 1) {
const innerCallback = needCalls(gotHandlers.length, () =>
callback(null, result)
);
for (const gotHandler of gotHandlers) {
gotHandler(result, innerCallback);
}
} else if (gotHandlers.length === 1) {
gotHandlers[0](result, () => callback(null, result));
} else {
callback(null, result);
}
});
}
/**
* @template T
* @param {string} identifier the cache identifier
* @param {Etag | null} etag the etag
* @param {T} data the value to store
* @param {CallbackCache<void>} callback signals when the value is stored
* @returns {void}
*/
store(identifier, etag, data, callback) {
this.hooks.store.callAsync(
identifier,
etag,
data,
makeWebpackErrorCallback(callback, "Cache.hooks.store")
);
}
/**
* After this method has succeeded the cache can only be restored when build dependencies are
* @param {Iterable<string>} dependencies list of all build dependencies
* @param {CallbackCache<void>} callback signals when the dependencies are stored
* @returns {void}
*/
storeBuildDependencies(dependencies, callback) {
this.hooks.storeBuildDependencies.callAsync(
dependencies,
makeWebpackErrorCallback(callback, "Cache.hooks.storeBuildDependencies")
);
}
/**
* @returns {void}
*/
beginIdle() {
this.hooks.beginIdle.call();
}
/**
* @param {CallbackCache<void>} callback signals when the call finishes
* @returns {void}
*/
endIdle(callback) {
this.hooks.endIdle.callAsync(
makeWebpackErrorCallback(callback, "Cache.hooks.endIdle")
);
}
/**
* @param {CallbackCache<void>} callback signals when the call finishes
* @returns {void}
*/
shutdown(callback) {
this.hooks.shutdown.callAsync(
makeWebpackErrorCallback(callback, "Cache.hooks.shutdown")
);
}
}
Cache.STAGE_MEMORY = -10;
Cache.STAGE_DEFAULT = 0;
Cache.STAGE_DISK = 10;
Cache.STAGE_NETWORK = 20;
module.exports = Cache;

345
assets_old/node_modules/webpack/lib/CacheFacade.js generated vendored Normal file
View file

@ -0,0 +1,345 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const asyncLib = require("neo-async");
const getLazyHashedEtag = require("./cache/getLazyHashedEtag");
const mergeEtags = require("./cache/mergeEtags");
/** @typedef {import("./Cache")} Cache */
/** @typedef {import("./Cache").Etag} Etag */
/** @typedef {import("./WebpackError")} WebpackError */
/** @typedef {import("./cache/getLazyHashedEtag").HashableObject} HashableObject */
/**
* @template T
* @callback CallbackCache
* @param {WebpackError=} err
* @param {T=} result
* @returns {void}
*/
/**
* @template T
* @callback CallbackNormalErrorCache
* @param {Error=} err
* @param {T=} result
* @returns {void}
*/
class MultiItemCache {
/**
* @param {ItemCacheFacade[]} items item caches
*/
constructor(items) {
this._items = items;
if (items.length === 1) return /** @type {any} */ (items[0]);
}
/**
* @template T
* @param {CallbackCache<T>} callback signals when the value is retrieved
* @returns {void}
*/
get(callback) {
const next = i => {
this._items[i].get((err, result) => {
if (err) return callback(err);
if (result !== undefined) return callback(null, result);
if (++i >= this._items.length) return callback();
next(i);
});
};
next(0);
}
/**
* @template T
* @returns {Promise<T>} promise with the data
*/
getPromise() {
const next = i => {
return this._items[i].getPromise().then(result => {
if (result !== undefined) return result;
if (++i < this._items.length) return next(i);
});
};
return next(0);
}
/**
* @template T
* @param {T} data the value to store
* @param {CallbackCache<void>} callback signals when the value is stored
* @returns {void}
*/
store(data, callback) {
asyncLib.each(
this._items,
(item, callback) => item.store(data, callback),
callback
);
}
/**
* @template T
* @param {T} data the value to store
* @returns {Promise<void>} promise signals when the value is stored
*/
storePromise(data) {
return Promise.all(
this._items.map(item => item.storePromise(data))
).then(() => {});
}
}
class ItemCacheFacade {
/**
* @param {Cache} cache the root cache
* @param {string} name the child cache item name
* @param {Etag | null} etag the etag
*/
constructor(cache, name, etag) {
this._cache = cache;
this._name = name;
this._etag = etag;
}
/**
* @template T
* @param {CallbackCache<T>} callback signals when the value is retrieved
* @returns {void}
*/
get(callback) {
this._cache.get(this._name, this._etag, callback);
}
/**
* @template T
* @returns {Promise<T>} promise with the data
*/
getPromise() {
return new Promise((resolve, reject) => {
this._cache.get(this._name, this._etag, (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
}
/**
* @template T
* @param {T} data the value to store
* @param {CallbackCache<void>} callback signals when the value is stored
* @returns {void}
*/
store(data, callback) {
this._cache.store(this._name, this._etag, data, callback);
}
/**
* @template T
* @param {T} data the value to store
* @returns {Promise<void>} promise signals when the value is stored
*/
storePromise(data) {
return new Promise((resolve, reject) => {
this._cache.store(this._name, this._etag, data, err => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
/**
* @template T
* @param {function(CallbackNormalErrorCache<T>): void} computer function to compute the value if not cached
* @param {CallbackNormalErrorCache<T>} callback signals when the value is retrieved
* @returns {void}
*/
provide(computer, callback) {
this.get((err, cacheEntry) => {
if (err) return callback(err);
if (cacheEntry !== undefined) return cacheEntry;
computer((err, result) => {
if (err) return callback(err);
this.store(result, err => {
if (err) return callback(err);
callback(null, result);
});
});
});
}
/**
* @template T
* @param {function(): Promise<T> | T} computer function to compute the value if not cached
* @returns {Promise<T>} promise with the data
*/
async providePromise(computer) {
const cacheEntry = await this.getPromise();
if (cacheEntry !== undefined) return cacheEntry;
const result = await computer();
await this.storePromise(result);
return result;
}
}
class CacheFacade {
/**
* @param {Cache} cache the root cache
* @param {string} name the child cache name
*/
constructor(cache, name) {
this._cache = cache;
this._name = name;
}
/**
* @param {string} name the child cache name#
* @returns {CacheFacade} child cache
*/
getChildCache(name) {
return new CacheFacade(this._cache, `${this._name}|${name}`);
}
/**
* @param {string} identifier the cache identifier
* @param {Etag | null} etag the etag
* @returns {ItemCacheFacade} item cache
*/
getItemCache(identifier, etag) {
return new ItemCacheFacade(
this._cache,
`${this._name}|${identifier}`,
etag
);
}
/**
* @param {HashableObject} obj an hashable object
* @returns {Etag} an etag that is lazy hashed
*/
getLazyHashedEtag(obj) {
return getLazyHashedEtag(obj);
}
/**
* @param {Etag} a an etag
* @param {Etag} b another etag
* @returns {Etag} an etag that represents both
*/
mergeEtags(a, b) {
return mergeEtags(a, b);
}
/**
* @template T
* @param {string} identifier the cache identifier
* @param {Etag | null} etag the etag
* @param {CallbackCache<T>} callback signals when the value is retrieved
* @returns {void}
*/
get(identifier, etag, callback) {
this._cache.get(`${this._name}|${identifier}`, etag, callback);
}
/**
* @template T
* @param {string} identifier the cache identifier
* @param {Etag | null} etag the etag
* @returns {Promise<T>} promise with the data
*/
getPromise(identifier, etag) {
return new Promise((resolve, reject) => {
this._cache.get(`${this._name}|${identifier}`, etag, (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
}
/**
* @template T
* @param {string} identifier the cache identifier
* @param {Etag | null} etag the etag
* @param {T} data the value to store
* @param {CallbackCache<void>} callback signals when the value is stored
* @returns {void}
*/
store(identifier, etag, data, callback) {
this._cache.store(`${this._name}|${identifier}`, etag, data, callback);
}
/**
* @template T
* @param {string} identifier the cache identifier
* @param {Etag | null} etag the etag
* @param {T} data the value to store
* @returns {Promise<void>} promise signals when the value is stored
*/
storePromise(identifier, etag, data) {
return new Promise((resolve, reject) => {
this._cache.store(`${this._name}|${identifier}`, etag, data, err => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
/**
* @template T
* @param {string} identifier the cache identifier
* @param {Etag | null} etag the etag
* @param {function(CallbackNormalErrorCache<T>): void} computer function to compute the value if not cached
* @param {CallbackNormalErrorCache<T>} callback signals when the value is retrieved
* @returns {void}
*/
provide(identifier, etag, computer, callback) {
this.get(identifier, etag, (err, cacheEntry) => {
if (err) return callback(err);
if (cacheEntry !== undefined) return cacheEntry;
computer((err, result) => {
if (err) return callback(err);
this.store(identifier, etag, result, err => {
if (err) return callback(err);
callback(null, result);
});
});
});
}
/**
* @template T
* @param {string} identifier the cache identifier
* @param {Etag | null} etag the etag
* @param {function(): Promise<T> | T} computer function to compute the value if not cached
* @returns {Promise<T>} promise with the data
*/
async providePromise(identifier, etag, computer) {
const cacheEntry = await this.getPromise(identifier, etag);
if (cacheEntry !== undefined) return cacheEntry;
const result = await computer();
await this.storePromise(identifier, etag, result);
return result;
}
}
module.exports = CacheFacade;
module.exports.ItemCacheFacade = ItemCacheFacade;
module.exports.MultiItemCache = MultiItemCache;

View file

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

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

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

1581
assets_old/node_modules/webpack/lib/ChunkGraph.js generated vendored Normal file

File diff suppressed because it is too large Load diff

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

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

View file

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

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

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

357
assets_old/node_modules/webpack/lib/CleanPlugin.js generated vendored Normal file
View file

@ -0,0 +1,357 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Sergey Melyukov @smelukov
*/
"use strict";
const asyncLib = require("neo-async");
const { validate } = require("schema-utils");
const { SyncBailHook } = require("tapable");
const Compilation = require("../lib/Compilation");
const { join } = require("./util/fs");
const memoize = require("./util/memoize");
const processAsyncTree = require("./util/processAsyncTree");
/** @typedef {import("../declarations/WebpackOptions").CleanOptions} CleanOptions */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./logging/Logger").Logger} Logger */
/** @typedef {import("./util/fs").OutputFileSystem} OutputFileSystem */
/** @typedef {(function(string):boolean)|RegExp} IgnoreItem */
/** @typedef {function(IgnoreItem): void} AddToIgnoreCallback */
/**
* @typedef {Object} CleanPluginCompilationHooks
* @property {SyncBailHook<[string], boolean>} keep when returning true the file/directory will be kept during cleaning, returning false will clean it and ignore the following plugins and config
*/
const getSchema = memoize(() => {
const { definitions } = require("../schemas/WebpackOptions.json");
return {
definitions,
oneOf: [{ $ref: "#/definitions/CleanOptions" }]
};
});
/**
* @param {OutputFileSystem} fs filesystem
* @param {string} outputPath output path
* @param {Set<string>} currentAssets filename of the current assets (must not start with .. or ., must only use / as path separator)
* @param {function(Error=, Set<string>=): void} callback returns the filenames of the assets that shouldn't be there
* @returns {void}
*/
const getDiffToFs = (fs, outputPath, currentAssets, callback) => {
const directories = new Set();
// get directories of assets
for (const asset of currentAssets) {
directories.add(asset.replace(/(^|\/)[^/]*$/, ""));
}
// and all parent directories
for (const directory of directories) {
directories.add(directory.replace(/(^|\/)[^/]*$/, ""));
}
const diff = new Set();
asyncLib.forEachLimit(
directories,
10,
(directory, callback) => {
fs.readdir(join(fs, outputPath, directory), (err, entries) => {
if (err) {
if (err.code === "ENOENT") return callback();
if (err.code === "ENOTDIR") {
diff.add(directory);
return callback();
}
return callback(err);
}
for (const entry of entries) {
const file = /** @type {string} */ (entry);
const filename = directory ? `${directory}/${file}` : file;
if (!directories.has(filename) && !currentAssets.has(filename)) {
diff.add(filename);
}
}
callback();
});
},
err => {
if (err) return callback(err);
callback(null, diff);
}
);
};
/**
* @param {Set<string>} currentAssets assets list
* @param {Set<string>} oldAssets old assets list
* @returns {Set<string>} diff
*/
const getDiffToOldAssets = (currentAssets, oldAssets) => {
const diff = new Set();
for (const asset of oldAssets) {
if (!currentAssets.has(asset)) diff.add(asset);
}
return diff;
};
/**
* @param {OutputFileSystem} fs filesystem
* @param {string} outputPath output path
* @param {boolean} dry only log instead of fs modification
* @param {Logger} logger logger
* @param {Set<string>} diff filenames of the assets that shouldn't be there
* @param {function(string): boolean} isKept check if the entry is ignored
* @param {function(Error=): void} callback callback
* @returns {void}
*/
const applyDiff = (fs, outputPath, dry, logger, diff, isKept, callback) => {
const log = msg => {
if (dry) {
logger.info(msg);
} else {
logger.log(msg);
}
};
/** @typedef {{ type: "check" | "unlink" | "rmdir", filename: string, parent: { remaining: number, job: Job } | undefined }} Job */
/** @type {Job[]} */
const jobs = Array.from(diff, filename => ({
type: "check",
filename,
parent: undefined
}));
processAsyncTree(
jobs,
10,
({ type, filename, parent }, push, callback) => {
const handleError = err => {
if (err.code === "ENOENT") {
log(`${filename} was removed during cleaning by something else`);
handleParent();
return callback();
}
return callback(err);
};
const handleParent = () => {
if (parent && --parent.remaining === 0) push(parent.job);
};
const path = join(fs, outputPath, filename);
switch (type) {
case "check":
if (isKept(filename)) {
// do not decrement parent entry as we don't want to delete the parent
log(`${filename} will be kept`);
return process.nextTick(callback);
}
fs.stat(path, (err, stats) => {
if (err) return handleError(err);
if (!stats.isDirectory()) {
push({
type: "unlink",
filename,
parent
});
return callback();
}
fs.readdir(path, (err, entries) => {
if (err) return handleError(err);
/** @type {Job} */
const deleteJob = {
type: "rmdir",
filename,
parent
};
if (entries.length === 0) {
push(deleteJob);
} else {
const parentToken = {
remaining: entries.length,
job: deleteJob
};
for (const entry of entries) {
const file = /** @type {string} */ (entry);
if (file.startsWith(".")) {
log(
`${filename} will be kept (dot-files will never be removed)`
);
continue;
}
push({
type: "check",
filename: `${filename}/${file}`,
parent: parentToken
});
}
}
return callback();
});
});
break;
case "rmdir":
log(`${filename} will be removed`);
if (dry) {
handleParent();
return process.nextTick(callback);
}
if (!fs.rmdir) {
logger.warn(
`${filename} can't be removed because output file system doesn't support removing directories (rmdir)`
);
return process.nextTick(callback);
}
fs.rmdir(path, err => {
if (err) return handleError(err);
handleParent();
callback();
});
break;
case "unlink":
log(`${filename} will be removed`);
if (dry) {
handleParent();
return process.nextTick(callback);
}
if (!fs.unlink) {
logger.warn(
`${filename} can't be removed because output file system doesn't support removing files (rmdir)`
);
return process.nextTick(callback);
}
fs.unlink(path, err => {
if (err) return handleError(err);
handleParent();
callback();
});
break;
}
},
callback
);
};
/** @type {WeakMap<Compilation, CleanPluginCompilationHooks>} */
const compilationHooksMap = new WeakMap();
class CleanPlugin {
/**
* @param {Compilation} compilation the compilation
* @returns {CleanPluginCompilationHooks} the attached hooks
*/
static getCompilationHooks(compilation) {
if (!(compilation instanceof Compilation)) {
throw new TypeError(
"The 'compilation' argument must be an instance of Compilation"
);
}
let hooks = compilationHooksMap.get(compilation);
if (hooks === undefined) {
hooks = {
/** @type {SyncBailHook<[string], boolean>} */
keep: new SyncBailHook(["ignore"])
};
compilationHooksMap.set(compilation, hooks);
}
return hooks;
}
/** @param {CleanOptions} [options] options */
constructor(options = {}) {
validate(getSchema(), options, {
name: "Clean Plugin",
baseDataPath: "options"
});
this.options = { dry: false, ...options };
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
const { dry, keep } = this.options;
const keepFn =
typeof keep === "function"
? keep
: typeof keep === "string"
? path => path.startsWith(keep)
: typeof keep === "object" && keep.test
? path => keep.test(path)
: () => false;
// We assume that no external modification happens while the compiler is active
// So we can store the old assets and only diff to them to avoid fs access on
// incremental builds
let oldAssets;
compiler.hooks.emit.tapAsync(
{
name: "CleanPlugin",
stage: 100
},
(compilation, callback) => {
const hooks = CleanPlugin.getCompilationHooks(compilation);
const logger = compilation.getLogger("webpack.CleanPlugin");
const fs = compiler.outputFileSystem;
if (!fs.readdir) {
return callback(
new Error(
"CleanPlugin: Output filesystem doesn't support listing directories (readdir)"
)
);
}
const currentAssets = new Set();
for (const asset of Object.keys(compilation.assets)) {
if (/^[A-Za-z]:\\|^\/|^\\\\/.test(asset)) continue;
let normalizedAsset;
let newNormalizedAsset = asset.replace(/\\/g, "/");
do {
normalizedAsset = newNormalizedAsset;
newNormalizedAsset = normalizedAsset.replace(
/(^|\/)(?!\.\.)[^/]+\/\.\.\//g,
"$1"
);
} while (newNormalizedAsset !== normalizedAsset);
if (normalizedAsset.startsWith("../")) continue;
currentAssets.add(normalizedAsset);
}
const outputPath = compilation.getPath(compiler.outputPath, {});
const isKept = path => {
const result = hooks.keep.call(path);
if (result !== undefined) return result;
return keepFn(path);
};
const diffCallback = (err, diff) => {
if (err) {
oldAssets = undefined;
return callback(err);
}
applyDiff(fs, outputPath, dry, logger, diff, isKept, err => {
if (err) {
oldAssets = undefined;
} else {
oldAssets = currentAssets;
}
callback(err);
});
};
if (oldAssets) {
diffCallback(null, getDiffToOldAssets(currentAssets, oldAssets));
} else {
getDiffToFs(fs, outputPath, currentAssets, diffCallback);
}
}
);
}
}
module.exports = CleanPlugin;

View file

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

View file

@ -0,0 +1,150 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { provide } = require("./util/MapHelpers");
const { first } = require("./util/SetHelpers");
const createHash = require("./util/createHash");
const { runtimeToString, RuntimeSpecMap } = require("./util/runtime");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
class CodeGenerationResults {
constructor() {
/** @type {Map<Module, RuntimeSpecMap<CodeGenerationResult>>} */
this.map = new Map();
}
/**
* @param {Module} module the module
* @param {RuntimeSpec} runtime runtime(s)
* @returns {CodeGenerationResult} the CodeGenerationResult
*/
get(module, runtime) {
const entry = this.map.get(module);
if (entry === undefined) {
throw new Error(
`No code generation entry for ${module.identifier()} (existing entries: ${Array.from(
this.map.keys(),
m => m.identifier()
).join(", ")})`
);
}
if (runtime === undefined) {
if (entry.size > 1) {
const results = new Set(entry.values());
if (results.size !== 1) {
throw new Error(
`No unique code generation entry for unspecified runtime for ${module.identifier()} (existing runtimes: ${Array.from(
entry.keys(),
r => runtimeToString(r)
).join(", ")}).
Caller might not support runtime-dependent code generation (opt-out via optimization.usedExports: "global").`
);
}
return first(results);
}
return entry.values().next().value;
}
const result = entry.get(runtime);
if (result === undefined) {
throw new Error(
`No code generation entry for runtime ${runtimeToString(
runtime
)} for ${module.identifier()} (existing runtimes: ${Array.from(
entry.keys(),
r => runtimeToString(r)
).join(", ")})`
);
}
return result;
}
/**
* @param {Module} module the module
* @param {RuntimeSpec} runtime runtime(s)
* @returns {boolean} true, when we have data for this
*/
has(module, runtime) {
const entry = this.map.get(module);
if (entry === undefined) {
return false;
}
if (runtime !== undefined) {
return entry.has(runtime);
} else if (entry.size > 1) {
const results = new Set(entry.values());
return results.size === 1;
} else {
return entry.size === 1;
}
}
/**
* @param {Module} module the module
* @param {RuntimeSpec} runtime runtime(s)
* @param {string} sourceType the source type
* @returns {Source} a source
*/
getSource(module, runtime, sourceType) {
return this.get(module, runtime).sources.get(sourceType);
}
/**
* @param {Module} module the module
* @param {RuntimeSpec} runtime runtime(s)
* @returns {ReadonlySet<string>} runtime requirements
*/
getRuntimeRequirements(module, runtime) {
return this.get(module, runtime).runtimeRequirements;
}
/**
* @param {Module} module the module
* @param {RuntimeSpec} runtime runtime(s)
* @param {string} key data key
* @returns {any} data generated by code generation
*/
getData(module, runtime, key) {
const data = this.get(module, runtime).data;
return data === undefined ? undefined : data.get(key);
}
/**
* @param {Module} module the module
* @param {RuntimeSpec} runtime runtime(s)
* @returns {any} hash of the code generation
*/
getHash(module, runtime) {
const info = this.get(module, runtime);
if (info.hash !== undefined) return info.hash;
const hash = createHash("md4");
for (const [type, source] of info.sources) {
hash.update(type);
source.updateHash(hash);
}
if (info.runtimeRequirements) {
for (const rr of info.runtimeRequirements) hash.update(rr);
}
return (info.hash = /** @type {string} */ (hash.digest("hex")));
}
/**
* @param {Module} module the module
* @param {RuntimeSpec} runtime runtime(s)
* @param {CodeGenerationResult} result result from module
* @returns {void}
*/
add(module, runtime, result) {
const map = provide(this.map, module, () => new RuntimeSpecMap());
map.set(runtime, result);
}
}
module.exports = CodeGenerationResults;

View file

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

View file

@ -0,0 +1,135 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const ConstDependency = require("./dependencies/ConstDependency");
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
const nestedWebpackRequireTag = Symbol("nested __webpack_require__");
class CompatibilityPlugin {
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(
"CompatibilityPlugin",
(compilation, { normalModuleFactory }) => {
compilation.dependencyTemplates.set(
ConstDependency,
new ConstDependency.Template()
);
normalModuleFactory.hooks.parser
.for("javascript/auto")
.tap("CompatibilityPlugin", (parser, parserOptions) => {
if (
parserOptions.browserify !== undefined &&
!parserOptions.browserify
)
return;
parser.hooks.call
.for("require")
.tap("CompatibilityPlugin", expr => {
// support for browserify style require delegator: "require(o, !0)"
if (expr.arguments.length !== 2) return;
const second = parser.evaluateExpression(expr.arguments[1]);
if (!second.isBoolean()) return;
if (second.asBool() !== true) return;
const dep = new ConstDependency("require", expr.callee.range);
dep.loc = expr.loc;
if (parser.state.current.dependencies.length > 0) {
const last =
parser.state.current.dependencies[
parser.state.current.dependencies.length - 1
];
if (
last.critical &&
last.options &&
last.options.request === "." &&
last.userRequest === "." &&
last.options.recursive
)
parser.state.current.dependencies.pop();
}
parser.state.module.addPresentationalDependency(dep);
return true;
});
});
/**
* @param {JavascriptParser} parser the parser
* @returns {void}
*/
const nestedWebpackRequireHandler = parser => {
parser.hooks.preStatement.tap("CompatibilityPlugin", statement => {
if (
statement.type === "FunctionDeclaration" &&
statement.id &&
statement.id.name === "__webpack_require__"
) {
const newName = `__nested_webpack_require_${statement.range[0]}__`;
parser.tagVariable(statement.id.name, nestedWebpackRequireTag, {
name: newName,
declaration: {
updated: false,
loc: statement.id.loc,
range: statement.id.range
}
});
return true;
}
});
parser.hooks.pattern
.for("__webpack_require__")
.tap("CompatibilityPlugin", pattern => {
const newName = `__nested_webpack_require_${pattern.range[0]}__`;
parser.tagVariable(pattern.name, nestedWebpackRequireTag, {
name: newName,
declaration: {
updated: false,
loc: pattern.loc,
range: pattern.range
}
});
return true;
});
parser.hooks.expression
.for(nestedWebpackRequireTag)
.tap("CompatibilityPlugin", expr => {
const { name, declaration } = parser.currentTagData;
if (!declaration.updated) {
const dep = new ConstDependency(name, declaration.range);
dep.loc = declaration.loc;
parser.state.module.addPresentationalDependency(dep);
declaration.updated = true;
}
const dep = new ConstDependency(name, expr.range);
dep.loc = expr.loc;
parser.state.module.addPresentationalDependency(dep);
return true;
});
};
normalModuleFactory.hooks.parser
.for("javascript/auto")
.tap("CompatibilityPlugin", nestedWebpackRequireHandler);
normalModuleFactory.hooks.parser
.for("javascript/dynamic")
.tap("CompatibilityPlugin", nestedWebpackRequireHandler);
normalModuleFactory.hooks.parser
.for("javascript/esm")
.tap("CompatibilityPlugin", nestedWebpackRequireHandler);
}
);
}
}
module.exports = CompatibilityPlugin;

4047
assets_old/node_modules/webpack/lib/Compilation.js generated vendored Normal file

File diff suppressed because it is too large Load diff

1109
assets_old/node_modules/webpack/lib/Compiler.js generated vendored Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,158 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
/** @typedef {import("./Module")} Module */
const MODULE_REFERENCE_REGEXP = /^__WEBPACK_MODULE_REFERENCE__(\d+)_([\da-f]+|ns)(_call)?(_directImport)?(?:_asiSafe(\d))?__$/;
const DEFAULT_EXPORT = "__WEBPACK_DEFAULT_EXPORT__";
const NAMESPACE_OBJECT_EXPORT = "__WEBPACK_NAMESPACE_OBJECT__";
/**
* @typedef {Object} ExternalModuleInfo
* @property {number} index
* @property {Module} module
*/
/**
* @typedef {Object} ConcatenatedModuleInfo
* @property {number} index
* @property {Module} module
* @property {Map<string, string>} exportMap mapping from export name to symbol
* @property {Map<string, string>} rawExportMap mapping from export name to symbol
* @property {string=} namespaceExportSymbol
*/
/** @typedef {ConcatenatedModuleInfo | ExternalModuleInfo} ModuleInfo */
/**
* @typedef {Object} ModuleReferenceOptions
* @property {string[]} ids the properties/exports of the module
* @property {boolean} call true, when this referenced export is called
* @property {boolean} directImport true, when this referenced export is directly imported (not via property access)
* @property {boolean | undefined} asiSafe if the position is ASI safe or unknown
*/
class ConcatenationScope {
/**
* @param {ModuleInfo[] | Map<Module, ModuleInfo>} modulesMap all module info by module
* @param {ConcatenatedModuleInfo} currentModule the current module info
*/
constructor(modulesMap, currentModule) {
this._currentModule = currentModule;
if (Array.isArray(modulesMap)) {
const map = new Map();
for (const info of modulesMap) {
map.set(info.module, info);
}
modulesMap = map;
}
this._modulesMap = modulesMap;
}
/**
* @param {Module} module the referenced module
* @returns {boolean} true, when it's in the scope
*/
isModuleInScope(module) {
return this._modulesMap.has(module);
}
/**
*
* @param {string} exportName name of the export
* @param {string} symbol identifier of the export in source code
*/
registerExport(exportName, symbol) {
if (!this._currentModule.exportMap) {
this._currentModule.exportMap = new Map();
}
if (!this._currentModule.exportMap.has(exportName)) {
this._currentModule.exportMap.set(exportName, symbol);
}
}
/**
*
* @param {string} exportName name of the export
* @param {string} expression expression to be used
*/
registerRawExport(exportName, expression) {
if (!this._currentModule.rawExportMap) {
this._currentModule.rawExportMap = new Map();
}
if (!this._currentModule.rawExportMap.has(exportName)) {
this._currentModule.rawExportMap.set(exportName, expression);
}
}
/**
* @param {string} symbol identifier of the export in source code
*/
registerNamespaceExport(symbol) {
this._currentModule.namespaceExportSymbol = symbol;
}
/**
*
* @param {Module} module the referenced module
* @param {Partial<ModuleReferenceOptions>} options options
* @returns {string} the reference as identifier
*/
createModuleReference(
module,
{ ids = undefined, call = false, directImport = false, asiSafe = false }
) {
const info = this._modulesMap.get(module);
const callFlag = call ? "_call" : "";
const directImportFlag = directImport ? "_directImport" : "";
const asiSafeFlag = asiSafe
? "_asiSafe1"
: asiSafe === false
? "_asiSafe0"
: "";
const exportData = ids
? Buffer.from(JSON.stringify(ids), "utf-8").toString("hex")
: "ns";
// a "._" is appended to allow "delete ...", which would cause a SyntaxError in strict mode
return `__WEBPACK_MODULE_REFERENCE__${info.index}_${exportData}${callFlag}${directImportFlag}${asiSafeFlag}__._`;
}
/**
* @param {string} name the identifier
* @returns {boolean} true, when it's an module reference
*/
static isModuleReference(name) {
return MODULE_REFERENCE_REGEXP.test(name);
}
/**
* @param {string} name the identifier
* @returns {ModuleReferenceOptions & { index: number }} parsed options and index
*/
static matchModuleReference(name) {
const match = MODULE_REFERENCE_REGEXP.exec(name);
if (!match) return null;
const index = +match[1];
const asiSafe = match[5];
return {
index,
ids:
match[2] === "ns"
? []
: JSON.parse(Buffer.from(match[2], "hex").toString("utf-8")),
call: !!match[3],
directImport: !!match[4],
asiSafe: asiSafe ? asiSafe === "1" : undefined
};
}
}
ConcatenationScope.DEFAULT_EXPORT = DEFAULT_EXPORT;
ConcatenationScope.NAMESPACE_OBJECT_EXPORT = NAMESPACE_OBJECT_EXPORT;
module.exports = ConcatenationScope;

View file

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

View file

@ -0,0 +1,109 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { ConcatSource, PrefixSource } = require("webpack-sources");
const InitFragment = require("./InitFragment");
const Template = require("./Template");
const { mergeRuntime } = require("./util/runtime");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("./Generator").GenerateContext} GenerateContext */
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
const wrapInCondition = (condition, source) => {
if (typeof source === "string") {
return Template.asString([
`if (${condition}) {`,
Template.indent(source),
"}",
""
]);
} else {
return new ConcatSource(
`if (${condition}) {\n`,
new PrefixSource("\t", source),
"}\n"
);
}
};
class ConditionalInitFragment extends InitFragment {
/**
* @param {string|Source} content the source code that will be included as initialization code
* @param {number} stage category of initialization code (contribute to order)
* @param {number} position position in the category (contribute to order)
* @param {string} key unique key to avoid emitting the same initialization code twice
* @param {RuntimeSpec | boolean} runtimeCondition in which runtime this fragment should be executed
* @param {string|Source=} endContent the source code that will be included at the end of the module
*/
constructor(
content,
stage,
position,
key,
runtimeCondition = true,
endContent
) {
super(content, stage, position, key, endContent);
this.runtimeCondition = runtimeCondition;
}
/**
* @param {GenerateContext} generateContext context for generate
* @returns {string|Source} the source code that will be included as initialization code
*/
getContent(generateContext) {
if (this.runtimeCondition === false || !this.content) return "";
if (this.runtimeCondition === true) return this.content;
const expr = generateContext.runtimeTemplate.runtimeConditionExpression({
chunkGraph: generateContext.chunkGraph,
runtimeRequirements: generateContext.runtimeRequirements,
runtime: generateContext.runtime,
runtimeCondition: this.runtimeCondition
});
if (expr === "true") return this.content;
return wrapInCondition(expr, this.content);
}
/**
* @param {GenerateContext} generateContext context for generate
* @returns {string|Source=} the source code that will be included at the end of the module
*/
getEndContent(generateContext) {
if (this.runtimeCondition === false || !this.endContent) return "";
if (this.runtimeCondition === true) return this.endContent;
const expr = generateContext.runtimeTemplate.runtimeConditionExpression({
chunkGraph: generateContext.chunkGraph,
runtimeRequirements: generateContext.runtimeRequirements,
runtime: generateContext.runtime,
runtimeCondition: this.runtimeCondition
});
if (expr === "true") return this.endContent;
return wrapInCondition(expr, this.endContent);
}
merge(other) {
if (this.runtimeCondition === true) return this;
if (other.runtimeCondition === true) return other;
if (this.runtimeCondition === false) return other;
if (other.runtimeCondition === false) return this;
const runtimeCondition = mergeRuntime(
this.runtimeCondition,
other.runtimeCondition
);
return new ConditionalInitFragment(
this.content,
this.stage,
this.position,
this.key,
runtimeCondition,
this.endContent
);
}
}
module.exports = ConditionalInitFragment;

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

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

View file

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

1078
assets_old/node_modules/webpack/lib/ContextModule.js generated vendored Normal file

File diff suppressed because it is too large Load diff

View file

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

View file

@ -0,0 +1,156 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const ContextElementDependency = require("./dependencies/ContextElementDependency");
const { join } = require("./util/fs");
class ContextReplacementPlugin {
constructor(
resourceRegExp,
newContentResource,
newContentRecursive,
newContentRegExp
) {
this.resourceRegExp = resourceRegExp;
if (typeof newContentResource === "function") {
this.newContentCallback = newContentResource;
} else if (
typeof newContentResource === "string" &&
typeof newContentRecursive === "object"
) {
this.newContentResource = newContentResource;
this.newContentCreateContextMap = (fs, callback) => {
callback(null, newContentRecursive);
};
} else if (
typeof newContentResource === "string" &&
typeof newContentRecursive === "function"
) {
this.newContentResource = newContentResource;
this.newContentCreateContextMap = newContentRecursive;
} else {
if (typeof newContentResource !== "string") {
newContentRegExp = newContentRecursive;
newContentRecursive = newContentResource;
newContentResource = undefined;
}
if (typeof newContentRecursive !== "boolean") {
newContentRegExp = newContentRecursive;
newContentRecursive = undefined;
}
this.newContentResource = newContentResource;
this.newContentRecursive = newContentRecursive;
this.newContentRegExp = newContentRegExp;
}
}
apply(compiler) {
const resourceRegExp = this.resourceRegExp;
const newContentCallback = this.newContentCallback;
const newContentResource = this.newContentResource;
const newContentRecursive = this.newContentRecursive;
const newContentRegExp = this.newContentRegExp;
const newContentCreateContextMap = this.newContentCreateContextMap;
compiler.hooks.contextModuleFactory.tap("ContextReplacementPlugin", cmf => {
cmf.hooks.beforeResolve.tap("ContextReplacementPlugin", result => {
if (!result) return;
if (resourceRegExp.test(result.request)) {
if (newContentResource !== undefined) {
result.request = newContentResource;
}
if (newContentRecursive !== undefined) {
result.recursive = newContentRecursive;
}
if (newContentRegExp !== undefined) {
result.regExp = newContentRegExp;
}
if (typeof newContentCallback === "function") {
newContentCallback(result);
} else {
for (const d of result.dependencies) {
if (d.critical) d.critical = false;
}
}
}
return result;
});
cmf.hooks.afterResolve.tap("ContextReplacementPlugin", result => {
if (!result) return;
if (resourceRegExp.test(result.resource)) {
if (newContentResource !== undefined) {
if (
newContentResource.startsWith("/") ||
(newContentResource.length > 1 && newContentResource[1] === ":")
) {
result.resource = newContentResource;
} else {
result.resource = join(
compiler.inputFileSystem,
result.resource,
newContentResource
);
}
}
if (newContentRecursive !== undefined) {
result.recursive = newContentRecursive;
}
if (newContentRegExp !== undefined) {
result.regExp = newContentRegExp;
}
if (typeof newContentCreateContextMap === "function") {
result.resolveDependencies = createResolveDependenciesFromContextMap(
newContentCreateContextMap
);
}
if (typeof newContentCallback === "function") {
const origResource = result.resource;
newContentCallback(result);
if (
result.resource !== origResource &&
!result.resource.startsWith("/") &&
(result.resource.length <= 1 || result.resource[1] !== ":")
) {
// When the function changed it to an relative path
result.resource = join(
compiler.inputFileSystem,
origResource,
result.resource
);
}
} else {
for (const d of result.dependencies) {
if (d.critical) d.critical = false;
}
}
}
return result;
});
});
}
}
const createResolveDependenciesFromContextMap = createContextMap => {
const resolveDependenciesFromContextMap = (fs, options, callback) => {
createContextMap(fs, (err, map) => {
if (err) return callback(err);
const dependencies = Object.keys(map).map(key => {
return new ContextElementDependency(
map[key] + options.resourceQuery + options.resourceFragment,
key,
options.category,
options.referencedExports
);
});
callback(null, dependencies);
});
};
return resolveDependenciesFromContextMap;
};
module.exports = ContextReplacementPlugin;

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

@ -0,0 +1,576 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const RuntimeGlobals = require("./RuntimeGlobals");
const WebpackError = require("./WebpackError");
const ConstDependency = require("./dependencies/ConstDependency");
const BasicEvaluatedExpression = require("./javascript/BasicEvaluatedExpression");
const {
evaluateToString,
toConstantDependency
} = require("./javascript/JavascriptParserHelpers");
/** @typedef {import("estree").Expression} Expression */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./NormalModule")} NormalModule */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
/** @typedef {null|undefined|RegExp|Function|string|number|boolean|bigint|undefined} CodeValuePrimitive */
/** @typedef {RecursiveArrayOrRecord<CodeValuePrimitive|RuntimeValue>} CodeValue */
/**
* @typedef {Object} RuntimeValueOptions
* @property {string[]=} fileDependencies
* @property {string[]=} contextDependencies
* @property {string[]=} missingDependencies
* @property {string[]=} buildDependencies
* @property {string|function(): string=} version
*/
class RuntimeValue {
/**
* @param {function({ module: NormalModule, key: string, readonly version: string | undefined }): CodeValuePrimitive} fn generator function
* @param {true | string[] | RuntimeValueOptions=} options options
*/
constructor(fn, options) {
this.fn = fn;
if (Array.isArray(options)) {
options = {
fileDependencies: options
};
}
this.options = options || {};
}
get fileDependencies() {
return this.options === true ? true : this.options.fileDependencies;
}
/**
* @param {JavascriptParser} parser the parser
* @param {Map<string, string>} valueCacheVersions valueCacheVersions
* @param {string} key the defined key
* @returns {CodeValuePrimitive} code
*/
exec(parser, valueCacheVersions, key) {
const buildInfo = parser.state.module.buildInfo;
if (this.options === true) {
buildInfo.cacheable = false;
} else {
if (this.options.fileDependencies) {
for (const dep of this.options.fileDependencies) {
buildInfo.fileDependencies.add(dep);
}
}
if (this.options.contextDependencies) {
for (const dep of this.options.contextDependencies) {
buildInfo.contextDependencies.add(dep);
}
}
if (this.options.missingDependencies) {
for (const dep of this.options.missingDependencies) {
buildInfo.missingDependencies.add(dep);
}
}
if (this.options.buildDependencies) {
for (const dep of this.options.buildDependencies) {
buildInfo.buildDependencies.add(dep);
}
}
}
return this.fn({
module: parser.state.module,
key,
get version() {
return valueCacheVersions.get(VALUE_DEP_PREFIX + key);
}
});
}
getCacheVersion() {
return this.options === true
? undefined
: (typeof this.options.version === "function"
? this.options.version()
: this.options.version) || "unset";
}
}
/**
* @param {any[]|{[k: string]: any}} obj obj
* @param {JavascriptParser} parser Parser
* @param {Map<string, string>} valueCacheVersions valueCacheVersions
* @param {string} key the defined key
* @param {RuntimeTemplate} runtimeTemplate the runtime template
* @param {boolean|undefined|null=} asiSafe asi safe (undefined: unknown, null: unneeded)
* @returns {string} code converted to string that evaluates
*/
const stringifyObj = (
obj,
parser,
valueCacheVersions,
key,
runtimeTemplate,
asiSafe
) => {
let code;
let arr = Array.isArray(obj);
if (arr) {
code = `[${obj
.map(code =>
toCode(code, parser, valueCacheVersions, key, runtimeTemplate, null)
)
.join(",")}]`;
} else {
code = `{${Object.keys(obj)
.map(key => {
const code = obj[key];
return (
JSON.stringify(key) +
":" +
toCode(code, parser, valueCacheVersions, key, runtimeTemplate, null)
);
})
.join(",")}}`;
}
switch (asiSafe) {
case null:
return code;
case true:
return arr ? code : `(${code})`;
case false:
return arr ? `;${code}` : `;(${code})`;
default:
return `Object(${code})`;
}
};
/**
* Convert code to a string that evaluates
* @param {CodeValue} code Code to evaluate
* @param {JavascriptParser} parser Parser
* @param {Map<string, string>} valueCacheVersions valueCacheVersions
* @param {string} key the defined key
* @param {RuntimeTemplate} runtimeTemplate the runtime template
* @param {boolean|undefined|null=} asiSafe asi safe (undefined: unknown, null: unneeded)
* @returns {string} code converted to string that evaluates
*/
const toCode = (
code,
parser,
valueCacheVersions,
key,
runtimeTemplate,
asiSafe
) => {
if (code === null) {
return "null";
}
if (code === undefined) {
return "undefined";
}
if (Object.is(code, -0)) {
return "-0";
}
if (code instanceof RuntimeValue) {
return toCode(
code.exec(parser, valueCacheVersions, key),
parser,
valueCacheVersions,
key,
runtimeTemplate,
asiSafe
);
}
if (code instanceof RegExp && code.toString) {
return code.toString();
}
if (typeof code === "function" && code.toString) {
return "(" + code.toString() + ")";
}
if (typeof code === "object") {
return stringifyObj(
code,
parser,
valueCacheVersions,
key,
runtimeTemplate,
asiSafe
);
}
if (typeof code === "bigint") {
return runtimeTemplate.supportsBigIntLiteral()
? `${code}n`
: `BigInt("${code}")`;
}
return code + "";
};
const toCacheVersion = code => {
if (code === null) {
return "null";
}
if (code === undefined) {
return "undefined";
}
if (Object.is(code, -0)) {
return "-0";
}
if (code instanceof RuntimeValue) {
return code.getCacheVersion();
}
if (code instanceof RegExp && code.toString) {
return code.toString();
}
if (typeof code === "function" && code.toString) {
return "(" + code.toString() + ")";
}
if (typeof code === "object") {
const items = Object.keys(code).map(key => ({
key,
value: toCacheVersion(code[key])
}));
if (items.some(({ value }) => value === undefined)) return undefined;
return `{${items.map(({ key, value }) => `${key}: ${value}`).join(", ")}}`;
}
if (typeof code === "bigint") {
return `${code}n`;
}
return code + "";
};
const VALUE_DEP_PREFIX = "webpack/DefinePlugin ";
class DefinePlugin {
/**
* Create a new define plugin
* @param {Record<string, CodeValue>} definitions A map of global object definitions
*/
constructor(definitions) {
this.definitions = definitions;
}
/**
* @param {function({ module: NormalModule, key: string, readonly version: string | undefined }): CodeValuePrimitive} fn generator function
* @param {true | string[] | RuntimeValueOptions=} options options
* @returns {RuntimeValue} runtime value
*/
static runtimeValue(fn, options) {
return new RuntimeValue(fn, options);
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
const definitions = this.definitions;
compiler.hooks.compilation.tap(
"DefinePlugin",
(compilation, { normalModuleFactory }) => {
compilation.dependencyTemplates.set(
ConstDependency,
new ConstDependency.Template()
);
const { runtimeTemplate } = compilation;
/**
* Handler
* @param {JavascriptParser} parser Parser
* @returns {void}
*/
const handler = parser => {
const addValueDependency = key => {
const { buildInfo } = parser.state.module;
if (!buildInfo.valueDependencies)
buildInfo.valueDependencies = new Map();
buildInfo.valueDependencies.set(
VALUE_DEP_PREFIX + key,
compilation.valueCacheVersions.get(VALUE_DEP_PREFIX + key)
);
};
const withValueDependency = (key, fn) => (...args) => {
addValueDependency(key);
return fn(...args);
};
/**
* Walk definitions
* @param {Object} definitions Definitions map
* @param {string} prefix Prefix string
* @returns {void}
*/
const walkDefinitions = (definitions, prefix) => {
Object.keys(definitions).forEach(key => {
const code = definitions[key];
if (
code &&
typeof code === "object" &&
!(code instanceof RuntimeValue) &&
!(code instanceof RegExp)
) {
walkDefinitions(code, prefix + key + ".");
applyObjectDefine(prefix + key, code);
return;
}
applyDefineKey(prefix, key);
applyDefine(prefix + key, code);
});
};
/**
* Apply define key
* @param {string} prefix Prefix
* @param {string} key Key
* @returns {void}
*/
const applyDefineKey = (prefix, key) => {
const splittedKey = key.split(".");
splittedKey.slice(1).forEach((_, i) => {
const fullKey = prefix + splittedKey.slice(0, i + 1).join(".");
parser.hooks.canRename.for(fullKey).tap("DefinePlugin", () => {
addValueDependency(key);
return true;
});
});
};
/**
* Apply Code
* @param {string} key Key
* @param {CodeValue} code Code
* @returns {void}
*/
const applyDefine = (key, code) => {
const originalKey = key;
const isTypeof = /^typeof\s+/.test(key);
if (isTypeof) key = key.replace(/^typeof\s+/, "");
let recurse = false;
let recurseTypeof = false;
if (!isTypeof) {
parser.hooks.canRename.for(key).tap("DefinePlugin", () => {
addValueDependency(originalKey);
return true;
});
parser.hooks.evaluateIdentifier
.for(key)
.tap("DefinePlugin", expr => {
/**
* this is needed in case there is a recursion in the DefinePlugin
* to prevent an endless recursion
* e.g.: new DefinePlugin({
* "a": "b",
* "b": "a"
* });
*/
if (recurse) return;
addValueDependency(originalKey);
recurse = true;
const res = parser.evaluate(
toCode(
code,
parser,
compilation.valueCacheVersions,
key,
runtimeTemplate,
null
)
);
recurse = false;
res.setRange(expr.range);
return res;
});
parser.hooks.expression.for(key).tap("DefinePlugin", expr => {
addValueDependency(originalKey);
const strCode = toCode(
code,
parser,
compilation.valueCacheVersions,
originalKey,
runtimeTemplate,
!parser.isAsiPosition(expr.range[0])
);
if (/__webpack_require__\s*(!?\.)/.test(strCode)) {
return toConstantDependency(parser, strCode, [
RuntimeGlobals.require
])(expr);
} else if (/__webpack_require__/.test(strCode)) {
return toConstantDependency(parser, strCode, [
RuntimeGlobals.requireScope
])(expr);
} else {
return toConstantDependency(parser, strCode)(expr);
}
});
}
parser.hooks.evaluateTypeof.for(key).tap("DefinePlugin", expr => {
/**
* this is needed in case there is a recursion in the DefinePlugin
* to prevent an endless recursion
* e.g.: new DefinePlugin({
* "typeof a": "typeof b",
* "typeof b": "typeof a"
* });
*/
if (recurseTypeof) return;
recurseTypeof = true;
addValueDependency(originalKey);
const codeCode = toCode(
code,
parser,
compilation.valueCacheVersions,
originalKey,
runtimeTemplate,
null
);
const typeofCode = isTypeof
? codeCode
: "typeof (" + codeCode + ")";
const res = parser.evaluate(typeofCode);
recurseTypeof = false;
res.setRange(expr.range);
return res;
});
parser.hooks.typeof.for(key).tap("DefinePlugin", expr => {
addValueDependency(originalKey);
const codeCode = toCode(
code,
parser,
compilation.valueCacheVersions,
originalKey,
runtimeTemplate,
null
);
const typeofCode = isTypeof
? codeCode
: "typeof (" + codeCode + ")";
const res = parser.evaluate(typeofCode);
if (!res.isString()) return;
return toConstantDependency(
parser,
JSON.stringify(res.string)
).bind(parser)(expr);
});
};
/**
* Apply Object
* @param {string} key Key
* @param {Object} obj Object
* @returns {void}
*/
const applyObjectDefine = (key, obj) => {
parser.hooks.canRename.for(key).tap("DefinePlugin", () => {
addValueDependency(key);
return true;
});
parser.hooks.evaluateIdentifier
.for(key)
.tap("DefinePlugin", expr => {
addValueDependency(key);
return new BasicEvaluatedExpression()
.setTruthy()
.setSideEffects(false)
.setRange(expr.range);
});
parser.hooks.evaluateTypeof
.for(key)
.tap(
"DefinePlugin",
withValueDependency(key, evaluateToString("object"))
);
parser.hooks.expression.for(key).tap("DefinePlugin", expr => {
addValueDependency(key);
const strCode = stringifyObj(
obj,
parser,
compilation.valueCacheVersions,
key,
runtimeTemplate,
!parser.isAsiPosition(expr.range[0])
);
if (/__webpack_require__\s*(!?\.)/.test(strCode)) {
return toConstantDependency(parser, strCode, [
RuntimeGlobals.require
])(expr);
} else if (/__webpack_require__/.test(strCode)) {
return toConstantDependency(parser, strCode, [
RuntimeGlobals.requireScope
])(expr);
} else {
return toConstantDependency(parser, strCode)(expr);
}
});
parser.hooks.typeof
.for(key)
.tap(
"DefinePlugin",
withValueDependency(
key,
toConstantDependency(parser, JSON.stringify("object"))
)
);
};
walkDefinitions(definitions, "");
};
normalModuleFactory.hooks.parser
.for("javascript/auto")
.tap("DefinePlugin", handler);
normalModuleFactory.hooks.parser
.for("javascript/dynamic")
.tap("DefinePlugin", handler);
normalModuleFactory.hooks.parser
.for("javascript/esm")
.tap("DefinePlugin", handler);
/**
* Walk definitions
* @param {Object} definitions Definitions map
* @param {string} prefix Prefix string
* @returns {void}
*/
const walkDefinitionsForValues = (definitions, prefix) => {
Object.keys(definitions).forEach(key => {
const code = definitions[key];
const version = toCacheVersion(code);
const name = VALUE_DEP_PREFIX + prefix + key;
const oldVersion = compilation.valueCacheVersions.get(name);
if (oldVersion === undefined) {
compilation.valueCacheVersions.set(name, version);
} else if (oldVersion !== version) {
const warning = new WebpackError(
`DefinePlugin\nConflicting values for '${prefix + key}'`
);
warning.details = `'${oldVersion}' !== '${version}'`;
warning.hideStack = true;
compilation.warnings.push(warning);
}
if (
code &&
typeof code === "object" &&
!(code instanceof RuntimeValue) &&
!(code instanceof RegExp)
) {
walkDefinitionsForValues(code, prefix + key + ".");
}
});
};
walkDefinitionsForValues(definitions, "");
}
);
}
}
module.exports = DefinePlugin;

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

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

View file

@ -0,0 +1,91 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const DelegatedModule = require("./DelegatedModule");
// options.source
// options.type
// options.context
// options.scope
// options.content
// options.associatedObjectForCache
class DelegatedModuleFactoryPlugin {
constructor(options) {
this.options = options;
options.type = options.type || "require";
options.extensions = options.extensions || ["", ".js", ".json", ".wasm"];
}
apply(normalModuleFactory) {
const scope = this.options.scope;
if (scope) {
normalModuleFactory.hooks.factorize.tapAsync(
"DelegatedModuleFactoryPlugin",
(data, callback) => {
const [dependency] = data.dependencies;
const { request } = dependency;
if (request && request.startsWith(`${scope}/`)) {
const innerRequest = "." + request.substr(scope.length);
let resolved;
if (innerRequest in this.options.content) {
resolved = this.options.content[innerRequest];
return callback(
null,
new DelegatedModule(
this.options.source,
resolved,
this.options.type,
innerRequest,
request
)
);
}
for (let i = 0; i < this.options.extensions.length; i++) {
const extension = this.options.extensions[i];
const requestPlusExt = innerRequest + extension;
if (requestPlusExt in this.options.content) {
resolved = this.options.content[requestPlusExt];
return callback(
null,
new DelegatedModule(
this.options.source,
resolved,
this.options.type,
requestPlusExt,
request + extension
)
);
}
}
}
return callback();
}
);
} else {
normalModuleFactory.hooks.module.tap(
"DelegatedModuleFactoryPlugin",
module => {
const request = module.libIdent(this.options);
if (request) {
if (request in this.options.content) {
const resolved = this.options.content[request];
return new DelegatedModule(
this.options.source,
resolved,
this.options.type,
request,
module
);
}
}
return module;
}
);
}
}
}
module.exports = DelegatedModuleFactoryPlugin;

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

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

View file

@ -0,0 +1,98 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./ChunkGroup")} ChunkGroup */
/** @typedef {import("./Dependency")} Dependency */
/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */
/** @typedef {import("./util/Hash")} Hash */
/** @typedef {(d: Dependency) => boolean} DependencyFilterFunction */
class DependenciesBlock {
constructor() {
/** @type {Dependency[]} */
this.dependencies = [];
/** @type {AsyncDependenciesBlock[]} */
this.blocks = [];
}
/**
* Adds a DependencyBlock to DependencyBlock relationship.
* This is used for when a Module has a AsyncDependencyBlock tie (for code-splitting)
*
* @param {AsyncDependenciesBlock} block block being added
* @returns {void}
*/
addBlock(block) {
this.blocks.push(block);
block.parent = this;
}
/**
* @param {Dependency} dependency dependency being tied to block.
* This is an "edge" pointing to another "node" on module graph.
* @returns {void}
*/
addDependency(dependency) {
this.dependencies.push(dependency);
}
/**
* @param {Dependency} dependency dependency being removed
* @returns {void}
*/
removeDependency(dependency) {
const idx = this.dependencies.indexOf(dependency);
if (idx >= 0) {
this.dependencies.splice(idx, 1);
}
}
/**
* Removes all dependencies and blocks
* @returns {void}
*/
clearDependenciesAndBlocks() {
this.dependencies.length = 0;
this.blocks.length = 0;
}
/**
* @param {Hash} hash the hash used to track dependencies
* @param {UpdateHashContext} context context
* @returns {void}
*/
updateHash(hash, context) {
for (const dep of this.dependencies) {
dep.updateHash(hash, context);
}
for (const block of this.blocks) {
block.updateHash(hash, context);
}
}
serialize({ write }) {
write(this.dependencies);
write(this.blocks);
}
deserialize({ read }) {
this.dependencies = read();
this.blocks = read();
for (const block of this.blocks) {
block.parent = this;
}
}
}
makeSerializable(DependenciesBlock, "webpack/lib/DependenciesBlock");
module.exports = DependenciesBlock;

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

@ -0,0 +1,251 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const memoize = require("./util/memoize");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
/** @typedef {import("./ModuleGraphConnection")} ModuleGraphConnection */
/** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
/** @typedef {import("./WebpackError")} WebpackError */
/** @typedef {import("./util/Hash")} Hash */
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
/**
* @typedef {Object} UpdateHashContext
* @property {ChunkGraph} chunkGraph
* @property {RuntimeSpec} runtime
* @property {RuntimeTemplate=} runtimeTemplate
*/
/**
* @typedef {Object} SourcePosition
* @property {number} line
* @property {number=} column
*/
/**
* @typedef {Object} RealDependencyLocation
* @property {SourcePosition} start
* @property {SourcePosition=} end
* @property {number=} index
*/
/**
* @typedef {Object} SyntheticDependencyLocation
* @property {string} name
* @property {number=} index
*/
/** @typedef {SyntheticDependencyLocation|RealDependencyLocation} DependencyLocation */
/**
* @typedef {Object} ExportSpec
* @property {string} name the name of the export
* @property {boolean=} canMangle can the export be renamed (defaults to true)
* @property {boolean=} terminalBinding is the export a terminal binding that should be checked for export star conflicts
* @property {(string | ExportSpec)[]=} exports nested exports
* @property {ModuleGraphConnection=} from when reexported: from which module
* @property {string[] | null=} export when reexported: from which export
* @property {boolean=} hidden export is not visible, because another export blends over it
*/
/**
* @typedef {Object} ExportsSpec
* @property {(string | ExportSpec)[] | true | null} exports exported names, true for unknown exports or null for no exports
* @property {Set<string>=} excludeExports when exports = true, list of unaffected exports
* @property {Set<string>=} hideExports list of maybe prior exposed, but now hidden exports
* @property {ModuleGraphConnection=} from when reexported: from which module
* @property {boolean=} canMangle can the export be renamed (defaults to true)
* @property {boolean=} terminalBinding are the exports terminal bindings that should be checked for export star conflicts
* @property {Module[]=} dependencies module on which the result depends on
*/
/**
* @typedef {Object} ReferencedExport
* @property {string[]} name name of the referenced export
* @property {boolean=} canMangle when false, referenced export can not be mangled, defaults to true
*/
const getIgnoredModule = memoize(() => {
const RawModule = require("./RawModule");
return new RawModule("/* (ignored) */", `ignored`, `(ignored)`);
});
class Dependency {
constructor() {
// TODO check if this can be moved into ModuleDependency
/** @type {boolean} */
this.weak = false;
// TODO check if this can be moved into ModuleDependency
/** @type {boolean} */
this.optional = false;
/** @type {DependencyLocation} */
this.loc = undefined;
}
/**
* @returns {string} a display name for the type of dependency
*/
get type() {
return "unknown";
}
/**
* @returns {string} a dependency category, typical categories are "commonjs", "amd", "esm"
*/
get category() {
return "unknown";
}
/**
* @returns {string | null} an identifier to merge equal requests
*/
getResourceIdentifier() {
return null;
}
/**
* Returns the referenced module and export
* @deprecated
* @param {ModuleGraph} moduleGraph module graph
* @returns {never} throws error
*/
getReference(moduleGraph) {
throw new Error(
"Dependency.getReference was removed in favor of Dependency.getReferencedExports, ModuleGraph.getModule and ModuleGraph.getConnection().active"
);
}
/**
* Returns list of exports referenced by this dependency
* @param {ModuleGraph} moduleGraph module graph
* @param {RuntimeSpec} runtime the runtime for which the module is analysed
* @returns {(string[] | ReferencedExport)[]} referenced exports
*/
getReferencedExports(moduleGraph, runtime) {
return Dependency.EXPORTS_OBJECT_REFERENCED;
}
/**
* @param {ModuleGraph} moduleGraph module graph
* @returns {null | false | function(ModuleGraphConnection, RuntimeSpec): ConnectionState} function to determine if the connection is active
*/
getCondition(moduleGraph) {
return null;
}
/**
* Returns the exported names
* @param {ModuleGraph} moduleGraph module graph
* @returns {ExportsSpec | undefined} export names
*/
getExports(moduleGraph) {
return undefined;
}
/**
* Returns warnings
* @param {ModuleGraph} moduleGraph module graph
* @returns {WebpackError[]} warnings
*/
getWarnings(moduleGraph) {
return null;
}
/**
* Returns errors
* @param {ModuleGraph} moduleGraph module graph
* @returns {WebpackError[]} errors
*/
getErrors(moduleGraph) {
return null;
}
/**
* Update the hash
* @param {Hash} hash hash to be updated
* @param {UpdateHashContext} context context
* @returns {void}
*/
updateHash(hash, context) {}
/**
* implement this method to allow the occurrence order plugin to count correctly
* @returns {number} count how often the id is used in this dependency
*/
getNumberOfIdOccurrences() {
return 1;
}
/**
* @param {ModuleGraph} moduleGraph the module graph
* @returns {ConnectionState} how this dependency connects the module to referencing modules
*/
getModuleEvaluationSideEffectsState(moduleGraph) {
return true;
}
/**
* @param {string} context context directory
* @returns {Module} a module
*/
createIgnoredModule(context) {
return getIgnoredModule();
}
serialize({ write }) {
write(this.weak);
write(this.optional);
write(this.loc);
}
deserialize({ read }) {
this.weak = read();
this.optional = read();
this.loc = read();
}
}
Dependency.NO_EXPORTS_REFERENCED = [];
Dependency.EXPORTS_OBJECT_REFERENCED = [[]];
Object.defineProperty(Dependency.prototype, "module", {
/**
* @deprecated
* @returns {never} throws
*/
get() {
throw new Error(
"module property was removed from Dependency (use compilation.moduleGraph.getModule(dependency) instead)"
);
},
/**
* @deprecated
* @returns {never} throws
*/
set() {
throw new Error(
"module property was removed from Dependency (use compilation.moduleGraph.updateModule(dependency, module) instead)"
);
}
});
Object.defineProperty(Dependency.prototype, "disconnect", {
get() {
throw new Error(
"disconnect was removed from Dependency (Dependency no longer carries graph specific information)"
);
}
});
module.exports = Dependency;

View file

@ -0,0 +1,47 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./ConcatenationScope")} ConcatenationScope */
/** @typedef {import("./Dependency")} Dependency */
/** @typedef {import("./Dependency").RuntimeSpec} RuntimeSpec */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @typedef {import("./InitFragment")} InitFragment */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
/**
* @typedef {Object} DependencyTemplateContext
* @property {RuntimeTemplate} runtimeTemplate the runtime template
* @property {DependencyTemplates} dependencyTemplates the dependency templates
* @property {ModuleGraph} moduleGraph the module graph
* @property {ChunkGraph} chunkGraph the chunk graph
* @property {Set<string>} runtimeRequirements the requirements for runtime
* @property {Module} module current module
* @property {RuntimeSpec} runtime current runtimes, for which code is generated
* @property {InitFragment[]} initFragments mutable array of init fragments for the current module
* @property {ConcatenationScope=} concatenationScope when in a concatenated module, information about other concatenated modules
*/
class DependencyTemplate {
/* istanbul ignore next */
/**
* @abstract
* @param {Dependency} dependency the dependency for which the template should be applied
* @param {ReplaceSource} source the current replace source which can be modified
* @param {DependencyTemplateContext} templateContext the context object
* @returns {void}
*/
apply(dependency, source, templateContext) {
const AbstractMethodError = require("./AbstractMethodError");
throw new AbstractMethodError();
}
}
module.exports = DependencyTemplate;

View file

@ -0,0 +1,62 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const createHash = require("./util/createHash");
/** @typedef {import("./Dependency")} Dependency */
/** @typedef {import("./DependencyTemplate")} DependencyTemplate */
/** @typedef {new (...args: any[]) => Dependency} DependencyConstructor */
class DependencyTemplates {
constructor() {
/** @type {Map<Function, DependencyTemplate>} */
this._map = new Map();
/** @type {string} */
this._hash = "31d6cfe0d16ae931b73c59d7e0c089c0";
}
/**
* @param {DependencyConstructor} dependency Constructor of Dependency
* @returns {DependencyTemplate} template for this dependency
*/
get(dependency) {
return this._map.get(dependency);
}
/**
* @param {DependencyConstructor} dependency Constructor of Dependency
* @param {DependencyTemplate} dependencyTemplate template for this dependency
* @returns {void}
*/
set(dependency, dependencyTemplate) {
this._map.set(dependency, dependencyTemplate);
}
/**
* @param {string} part additional hash contributor
* @returns {void}
*/
updateHash(part) {
const hash = createHash("md4");
hash.update(this._hash);
hash.update(part);
this._hash = /** @type {string} */ (hash.digest("hex"));
}
getHash() {
return this._hash;
}
clone() {
const newInstance = new DependencyTemplates();
newInstance._map = new Map(this._map);
newInstance._hash = this._hash;
return newInstance;
}
}
module.exports = DependencyTemplates;

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

@ -0,0 +1,55 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const DllModuleFactory = require("./DllModuleFactory");
const DllEntryDependency = require("./dependencies/DllEntryDependency");
const EntryDependency = require("./dependencies/EntryDependency");
class DllEntryPlugin {
constructor(context, entries, options) {
this.context = context;
this.entries = entries;
this.options = options;
}
apply(compiler) {
compiler.hooks.compilation.tap(
"DllEntryPlugin",
(compilation, { normalModuleFactory }) => {
const dllModuleFactory = new DllModuleFactory();
compilation.dependencyFactories.set(
DllEntryDependency,
dllModuleFactory
);
compilation.dependencyFactories.set(
EntryDependency,
normalModuleFactory
);
}
);
compiler.hooks.make.tapAsync("DllEntryPlugin", (compilation, callback) => {
compilation.addEntry(
this.context,
new DllEntryDependency(
this.entries.map((e, idx) => {
const dep = new EntryDependency(e);
dep.loc = {
name: this.options.name,
index: idx
};
return dep;
}),
this.options.name
),
this.options,
callback
);
});
}
}
module.exports = DllEntryPlugin;

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

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

View file

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

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

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

View file

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

View file

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

View file

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

67
assets_old/node_modules/webpack/lib/EntryPlugin.js generated vendored Normal file
View file

@ -0,0 +1,67 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const EntryDependency = require("./dependencies/EntryDependency");
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */
class EntryPlugin {
/**
* An entry plugin which will handle
* creation of the EntryDependency
*
* @param {string} context context path
* @param {string} entry entry path
* @param {EntryOptions | string} options entry options (passing a string is deprecated)
*/
constructor(context, entry, options) {
this.context = context;
this.entry = entry;
this.options = options || "";
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(
"EntryPlugin",
(compilation, { normalModuleFactory }) => {
compilation.dependencyFactories.set(
EntryDependency,
normalModuleFactory
);
}
);
compiler.hooks.make.tapAsync("EntryPlugin", (compilation, callback) => {
const { entry, options, context } = this;
const dep = EntryPlugin.createDependency(entry, options);
compilation.addEntry(context, dep, options, err => {
callback(err);
});
});
}
/**
* @param {string} entry entry request
* @param {EntryOptions | string} options entry options (passing string is deprecated)
* @returns {EntryDependency} the dependency
*/
static createDependency(entry, options) {
const dep = new EntryDependency(entry);
// TODO webpack 6 remove string option
dep.loc = { name: typeof options === "object" ? options.name : options };
return dep;
}
}
module.exports = EntryPlugin;

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

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

View file

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

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

@ -0,0 +1,61 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const loaderFlag = "LOADER_EXECUTION";
const webpackOptionsFlag = "WEBPACK_OPTIONS";
exports.cutOffByFlag = (stack, flag) => {
stack = stack.split("\n");
for (let i = 0; i < stack.length; i++) {
if (stack[i].includes(flag)) {
stack.length = i;
}
}
return stack.join("\n");
};
exports.cutOffLoaderExecution = stack =>
exports.cutOffByFlag(stack, loaderFlag);
exports.cutOffWebpackOptions = stack =>
exports.cutOffByFlag(stack, webpackOptionsFlag);
exports.cutOffMultilineMessage = (stack, message) => {
stack = stack.split("\n");
message = message.split("\n");
const result = [];
stack.forEach((line, idx) => {
if (!line.includes(message[idx])) result.push(line);
});
return result.join("\n");
};
exports.cutOffMessage = (stack, message) => {
const nextLine = stack.indexOf("\n");
if (nextLine === -1) {
return stack === message ? "" : stack;
} else {
const firstLine = stack.substr(0, nextLine);
return firstLine === message ? stack.substr(nextLine + 1) : stack;
}
};
exports.cleanUp = (stack, message) => {
stack = exports.cutOffLoaderExecution(stack);
stack = exports.cutOffMessage(stack, message);
return stack;
};
exports.cleanUpWebpackOptions = (stack, message) => {
stack = exports.cutOffWebpackOptions(stack);
stack = exports.cutOffMultilineMessage(stack, message);
return stack;
};

View file

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

View file

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

1481
assets_old/node_modules/webpack/lib/ExportsInfo.js generated vendored Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,71 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const ConstDependency = require("./dependencies/ConstDependency");
const ExportsInfoDependency = require("./dependencies/ExportsInfoDependency");
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
class ExportsInfoApiPlugin {
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(
"ExportsInfoApiPlugin",
(compilation, { normalModuleFactory }) => {
compilation.dependencyTemplates.set(
ExportsInfoDependency,
new ExportsInfoDependency.Template()
);
/**
* @param {JavascriptParser} parser the parser
* @returns {void}
*/
const handler = parser => {
parser.hooks.expressionMemberChain
.for("__webpack_exports_info__")
.tap("ExportsInfoApiPlugin", (expr, members) => {
const dep =
members.length >= 2
? new ExportsInfoDependency(
expr.range,
members.slice(0, -1),
members[members.length - 1]
)
: new ExportsInfoDependency(expr.range, null, members[0]);
dep.loc = expr.loc;
parser.state.module.addDependency(dep);
return true;
});
parser.hooks.expression
.for("__webpack_exports_info__")
.tap("ExportsInfoApiPlugin", expr => {
const dep = new ConstDependency("true", expr.range);
dep.loc = expr.loc;
parser.state.module.addPresentationalDependency(dep);
return true;
});
};
normalModuleFactory.hooks.parser
.for("javascript/auto")
.tap("ExportsInfoApiPlugin", handler);
normalModuleFactory.hooks.parser
.for("javascript/dynamic")
.tap("ExportsInfoApiPlugin", handler);
normalModuleFactory.hooks.parser
.for("javascript/esm")
.tap("ExportsInfoApiPlugin", handler);
}
);
}
}
module.exports = ExportsInfoApiPlugin;

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

@ -0,0 +1,497 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { OriginalSource, RawSource } = require("webpack-sources");
const ConcatenationScope = require("./ConcatenationScope");
const Module = require("./Module");
const RuntimeGlobals = require("./RuntimeGlobals");
const Template = require("./Template");
const StaticExportsDependency = require("./dependencies/StaticExportsDependency");
const extractUrlAndGlobal = require("./util/extractUrlAndGlobal");
const makeSerializable = require("./util/makeSerializable");
const propertyAccess = require("./util/propertyAccess");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */
/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("./Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */
/** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */
/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */
/** @typedef {import("./RequestShortener")} RequestShortener */
/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
/** @typedef {import("./WebpackError")} WebpackError */
/** @typedef {import("./util/Hash")} Hash */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
/**
* @typedef {Object} SourceData
* @property {boolean=} iife
* @property {string=} init
* @property {string} expression
*/
/**
* @param {string|string[]} variableName the variable name or path
* @param {string} type the module system
* @returns {SourceData} the generated source
*/
const getSourceForGlobalVariableExternal = (variableName, type) => {
if (!Array.isArray(variableName)) {
// make it an array as the look up works the same basically
variableName = [variableName];
}
// needed for e.g. window["some"]["thing"]
const objectLookup = variableName.map(r => `[${JSON.stringify(r)}]`).join("");
return {
iife: type === "this",
expression: `${type}${objectLookup}`
};
};
/**
* @param {string|string[]} moduleAndSpecifiers the module request
* @returns {SourceData} the generated source
*/
const getSourceForCommonJsExternal = moduleAndSpecifiers => {
if (!Array.isArray(moduleAndSpecifiers)) {
return {
expression: `require(${JSON.stringify(moduleAndSpecifiers)});`
};
}
const moduleName = moduleAndSpecifiers[0];
return {
expression: `require(${JSON.stringify(moduleName)})${propertyAccess(
moduleAndSpecifiers,
1
)};`
};
};
/**
* @param {string|string[]} moduleAndSpecifiers the module request
* @param {RuntimeTemplate} runtimeTemplate the runtime template
* @returns {SourceData} the generated source
*/
const getSourceForImportExternal = (moduleAndSpecifiers, runtimeTemplate) => {
const importName = runtimeTemplate.outputOptions.importFunctionName;
if (!runtimeTemplate.supportsDynamicImport() && importName === "import") {
throw new Error(
"The target environment doesn't support 'import()' so it's not possible to use external type 'import'"
);
}
if (!Array.isArray(moduleAndSpecifiers)) {
return {
expression: `${importName}(${JSON.stringify(moduleAndSpecifiers)});`
};
}
if (moduleAndSpecifiers.length === 1) {
return {
expression: `${importName}(${JSON.stringify(moduleAndSpecifiers[0])});`
};
}
const moduleName = moduleAndSpecifiers[0];
return {
expression: `${importName}(${JSON.stringify(
moduleName
)}).then(${runtimeTemplate.returningFunction(
`module${propertyAccess(moduleAndSpecifiers, 1)}`,
"module"
)});`
};
};
/**
* @param {string|string[]} urlAndGlobal the script request
* @param {RuntimeTemplate} runtimeTemplate the runtime template
* @returns {SourceData} the generated source
*/
const getSourceForScriptExternal = (urlAndGlobal, runtimeTemplate) => {
if (typeof urlAndGlobal === "string") {
urlAndGlobal = extractUrlAndGlobal(urlAndGlobal);
}
const url = urlAndGlobal[0];
const globalName = urlAndGlobal[1];
return {
init: "var __webpack_error__ = new Error();",
expression: `new Promise(${runtimeTemplate.basicFunction(
"resolve, reject",
[
`if(typeof ${globalName} !== "undefined") return resolve();`,
`${RuntimeGlobals.loadScript}(${JSON.stringify(
url
)}, ${runtimeTemplate.basicFunction("event", [
`if(typeof ${globalName} !== "undefined") return resolve();`,
"var errorType = event && (event.type === 'load' ? 'missing' : event.type);",
"var realSrc = event && event.target && event.target.src;",
"__webpack_error__.message = 'Loading script failed.\\n(' + errorType + ': ' + realSrc + ')';",
"__webpack_error__.name = 'ScriptExternalLoadError';",
"__webpack_error__.type = errorType;",
"__webpack_error__.request = realSrc;",
"reject(__webpack_error__);"
])}, ${JSON.stringify(globalName)});`
]
)}).then(${runtimeTemplate.returningFunction(
`${globalName}${propertyAccess(urlAndGlobal, 2)}`
)})`
};
};
/**
* @param {string} variableName the variable name to check
* @param {string} request the request path
* @param {RuntimeTemplate} runtimeTemplate the runtime template
* @returns {string} the generated source
*/
const checkExternalVariable = (variableName, request, runtimeTemplate) => {
return `if(typeof ${variableName} === 'undefined') { ${runtimeTemplate.throwMissingModuleErrorBlock(
{ request }
)} }\n`;
};
/**
* @param {string|number} id the module id
* @param {boolean} optional true, if the module is optional
* @param {string|string[]} request the request path
* @param {RuntimeTemplate} runtimeTemplate the runtime template
* @returns {SourceData} the generated source
*/
const getSourceForAmdOrUmdExternal = (
id,
optional,
request,
runtimeTemplate
) => {
const externalVariable = `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier(
`${id}`
)}__`;
return {
init: optional
? checkExternalVariable(
externalVariable,
Array.isArray(request) ? request.join(".") : request,
runtimeTemplate
)
: undefined,
expression: externalVariable
};
};
/**
* @param {boolean} optional true, if the module is optional
* @param {string|string[]} request the request path
* @param {RuntimeTemplate} runtimeTemplate the runtime template
* @returns {SourceData} the generated source
*/
const getSourceForDefaultCase = (optional, request, runtimeTemplate) => {
if (!Array.isArray(request)) {
// make it an array as the look up works the same basically
request = [request];
}
const variableName = request[0];
const objectLookup = propertyAccess(request, 1);
return {
init: optional
? checkExternalVariable(variableName, request.join("."), runtimeTemplate)
: undefined,
expression: `${variableName}${objectLookup}`
};
};
const TYPES = new Set(["javascript"]);
const RUNTIME_REQUIREMENTS = new Set([RuntimeGlobals.module]);
const RUNTIME_REQUIREMENTS_FOR_SCRIPT = new Set([
RuntimeGlobals.module,
RuntimeGlobals.loadScript
]);
const RUNTIME_REQUIREMENTS_CONCATENATED = new Set([]);
class ExternalModule extends Module {
constructor(request, type, userRequest) {
super("javascript/dynamic", null);
// Info from Factory
/** @type {string | string[] | Record<string, string | string[]>} */
this.request = request;
/** @type {string} */
this.externalType = type;
/** @type {string} */
this.userRequest = userRequest;
}
/**
* @returns {Set<string>} types available (do not mutate)
*/
getSourceTypes() {
return TYPES;
}
/**
* @param {LibIdentOptions} options options
* @returns {string | null} an identifier for library inclusion
*/
libIdent(options) {
return this.userRequest;
}
/**
* @param {Chunk} chunk the chunk which condition should be checked
* @param {Compilation} compilation the compilation
* @returns {boolean} true, if the chunk is ok for the module
*/
chunkCondition(chunk, { chunkGraph }) {
return chunkGraph.getNumberOfEntryModules(chunk) > 0;
}
/**
* @returns {string} a unique identifier of the module
*/
identifier() {
return "external " + JSON.stringify(this.request);
}
/**
* @param {RequestShortener} requestShortener the request shortener
* @returns {string} a user readable identifier of the module
*/
readableIdentifier(requestShortener) {
return "external " + JSON.stringify(this.request);
}
/**
* @param {NeedBuildContext} context context info
* @param {function(WebpackError=, boolean=): void} callback callback function, returns true, if the module needs a rebuild
* @returns {void}
*/
needBuild(context, callback) {
return callback(null, !this.buildMeta);
}
/**
* @param {WebpackOptions} options webpack options
* @param {Compilation} compilation the compilation
* @param {ResolverWithOptions} resolver the resolver
* @param {InputFileSystem} fs the file system
* @param {function(WebpackError=): void} callback callback function
* @returns {void}
*/
build(options, compilation, resolver, fs, callback) {
this.buildMeta = {
async: false,
exportsType: undefined
};
this.buildInfo = {
strict: this.externalType !== "this",
topLevelDeclarations: new Set()
};
this.buildMeta.exportsType = "dynamic";
let canMangle = false;
this.clearDependenciesAndBlocks();
switch (this.externalType) {
case "system":
if (!Array.isArray(this.request) || this.request.length === 1) {
this.buildMeta.exportsType = "namespace";
canMangle = true;
}
break;
case "promise":
this.buildMeta.async = true;
break;
case "import":
this.buildMeta.async = true;
if (!Array.isArray(this.request) || this.request.length === 1) {
this.buildMeta.exportsType = "namespace";
canMangle = false;
}
break;
case "script":
this.buildMeta.async = true;
break;
}
this.addDependency(new StaticExportsDependency(true, canMangle));
callback();
}
/**
* @param {ConcatenationBailoutReasonContext} context context
* @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated
*/
getConcatenationBailoutReason({ moduleGraph }) {
switch (this.externalType) {
case "amd":
case "amd-require":
case "umd":
case "umd2":
case "system":
case "jsonp":
return `${this.externalType} externals can't be concatenated`;
}
return undefined;
}
getSourceData(runtimeTemplate, moduleGraph, chunkGraph) {
const request =
typeof this.request === "object" && !Array.isArray(this.request)
? this.request[this.externalType]
: this.request;
switch (this.externalType) {
case "this":
case "window":
case "self":
return getSourceForGlobalVariableExternal(request, this.externalType);
case "global":
return getSourceForGlobalVariableExternal(
request,
runtimeTemplate.outputOptions.globalObject
);
case "commonjs":
case "commonjs2":
case "commonjs-module":
return getSourceForCommonJsExternal(request);
case "amd":
case "amd-require":
case "umd":
case "umd2":
case "system":
case "jsonp":
return getSourceForAmdOrUmdExternal(
chunkGraph.getModuleId(this),
this.isOptional(moduleGraph),
request,
runtimeTemplate
);
case "import":
return getSourceForImportExternal(request, runtimeTemplate);
case "script":
return getSourceForScriptExternal(request, runtimeTemplate);
case "module":
if (!runtimeTemplate.supportsEcmaScriptModuleSyntax()) {
throw new Error(
"The target environment doesn't support EcmaScriptModule syntax so it's not possible to use external type 'module'"
);
}
throw new Error("Module external type is not implemented yet");
case "var":
case "promise":
case "const":
case "let":
case "assign":
default:
return getSourceForDefaultCase(
this.isOptional(moduleGraph),
request,
runtimeTemplate
);
}
}
/**
* @param {CodeGenerationContext} context context for code generation
* @returns {CodeGenerationResult} result
*/
codeGeneration({
runtimeTemplate,
moduleGraph,
chunkGraph,
concatenationScope
}) {
const sourceData = this.getSourceData(
runtimeTemplate,
moduleGraph,
chunkGraph
);
let sourceString = sourceData.expression;
if (sourceData.iife)
sourceString = `(function() { return ${sourceString}; }())`;
if (concatenationScope) {
sourceString = `${runtimeTemplate.supportsConst() ? "const" : "var"} ${
ConcatenationScope.NAMESPACE_OBJECT_EXPORT
} = ${sourceString};`;
concatenationScope.registerNamespaceExport(
ConcatenationScope.NAMESPACE_OBJECT_EXPORT
);
} else {
sourceString = `module.exports = ${sourceString};`;
}
if (sourceData.init) sourceString = `${sourceData.init}\n${sourceString}`;
const sources = new Map();
if (this.useSourceMap || this.useSimpleSourceMap) {
sources.set(
"javascript",
new OriginalSource(sourceString, this.identifier())
);
} else {
sources.set("javascript", new RawSource(sourceString));
}
return {
sources,
runtimeRequirements: concatenationScope
? RUNTIME_REQUIREMENTS_CONCATENATED
: this.externalType === "script"
? RUNTIME_REQUIREMENTS_FOR_SCRIPT
: RUNTIME_REQUIREMENTS
};
}
/**
* @param {string=} type the source type for which the size should be estimated
* @returns {number} the estimated size of the module (must be non-zero)
*/
size(type) {
return 42;
}
/**
* @param {Hash} hash the hash used to track dependencies
* @param {UpdateHashContext} context context
* @returns {void}
*/
updateHash(hash, context) {
const { chunkGraph } = context;
hash.update(this.externalType);
hash.update(JSON.stringify(this.request));
hash.update(
JSON.stringify(Boolean(this.isOptional(chunkGraph.moduleGraph)))
);
super.updateHash(hash, context);
}
serialize(context) {
const { write } = context;
write(this.request);
write(this.externalType);
write(this.userRequest);
super.serialize(context);
}
deserialize(context) {
const { read } = context;
this.request = read();
this.externalType = read();
this.userRequest = read();
super.deserialize(context);
}
}
makeSerializable(ExternalModule, "webpack/lib/ExternalModule");
module.exports = ExternalModule;

View file

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

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

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

2846
assets_old/node_modules/webpack/lib/FileSystemInfo.js generated vendored Normal file

File diff suppressed because it is too large Load diff

View file

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

View file

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

View file

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

View file

@ -0,0 +1,53 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { getEntryRuntime } = require("./util/runtime");
/** @typedef {import("./Compiler")} Compiler */
class FlagEntryExportAsUsedPlugin {
constructor(nsObjectUsed, explanation) {
this.nsObjectUsed = nsObjectUsed;
this.explanation = explanation;
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.thisCompilation.tap(
"FlagEntryExportAsUsedPlugin",
compilation => {
const moduleGraph = compilation.moduleGraph;
compilation.hooks.seal.tap("FlagEntryExportAsUsedPlugin", () => {
for (const [
entryName,
{ dependencies: deps, options }
] of compilation.entries) {
const runtime = getEntryRuntime(compilation, entryName, options);
for (const dep of deps) {
const module = moduleGraph.getModule(dep);
if (module) {
const exportsInfo = moduleGraph.getExportsInfo(module);
if (this.nsObjectUsed) {
exportsInfo.setUsedInUnknownWay(runtime);
} else {
exportsInfo.setAllKnownExportsUsed(runtime);
}
moduleGraph.addExtraReason(module, this.explanation);
}
}
}
});
}
);
}
}
module.exports = FlagEntryExportAsUsedPlugin;

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

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

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

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

View file

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

View file

@ -0,0 +1,94 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Sean Larkin @thelarkinn
*/
"use strict";
const WebpackError = require("./WebpackError");
/** @typedef {import("./Module")} Module */
/**
* @template T
* @callback Callback
* @param {Error=} err
* @param {T=} stats
* @returns {void}
*/
class HookWebpackError extends WebpackError {
/**
* Creates an instance of HookWebpackError.
* @param {Error} error inner error
* @param {string} hook name of hook
*/
constructor(error, hook) {
super(error.message);
this.name = "HookWebpackError";
this.hook = hook;
this.error = error;
this.hideStack = true;
this.details = `caused by plugins in ${hook}\n${error.stack}`;
Error.captureStackTrace(this, this.constructor);
this.stack += `\n-- inner error --\n${error.stack}`;
}
}
module.exports = HookWebpackError;
/**
* @param {Error} error an error
* @param {string} hook name of the hook
* @returns {WebpackError} a webpack error
*/
const makeWebpackError = (error, hook) => {
if (error instanceof WebpackError) return error;
return new HookWebpackError(error, hook);
};
module.exports.makeWebpackError = makeWebpackError;
/**
* @template T
* @param {function(WebpackError=, T=): void} callback webpack error callback
* @param {string} hook name of hook
* @returns {Callback<T>} generic callback
*/
const makeWebpackErrorCallback = (callback, hook) => {
return (err, result) => {
if (err) {
if (err instanceof WebpackError) {
callback(err);
return;
}
callback(new HookWebpackError(err, hook));
return;
}
callback(null, result);
};
};
module.exports.makeWebpackErrorCallback = makeWebpackErrorCallback;
/**
* @template T
* @param {function(): T} fn function which will be wrapping in try catch
* @param {string} hook name of hook
* @returns {T} the result
*/
const tryRunOrWebpackError = (fn, hook) => {
let r;
try {
r = fn();
} catch (err) {
if (err instanceof WebpackError) {
throw err;
}
throw new HookWebpackError(err, hook);
}
return r;
};
module.exports.tryRunOrWebpackError = tryRunOrWebpackError;

View file

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

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

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

View file

@ -0,0 +1,39 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Ivan Kopeykin @vankop
*/
"use strict";
const ModuleFactory = require("./ModuleFactory");
/** @typedef {import("./ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */
/** @typedef {import("./ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */
/** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */
/**
* Ignores error when module is unresolved
*/
class IgnoreErrorModuleFactory extends ModuleFactory {
/**
* @param {NormalModuleFactory} normalModuleFactory normalModuleFactory instance
*/
constructor(normalModuleFactory) {
super();
this.normalModuleFactory = normalModuleFactory;
}
/**
* @param {ModuleFactoryCreateData} data data object
* @param {function(Error=, ModuleFactoryResult=): void} callback callback
* @returns {void}
*/
create(data, callback) {
this.normalModuleFactory.create(data, (err, result) => {
return callback(null, result);
});
}
}
module.exports = IgnoreErrorModuleFactory;

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

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

View file

@ -0,0 +1,39 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
/** @typedef {import("../declarations/WebpackOptions").IgnoreWarningsNormalized} IgnoreWarningsNormalized */
/** @typedef {import("./Compiler")} Compiler */
class IgnoreWarningsPlugin {
/**
* @param {IgnoreWarningsNormalized} ignoreWarnings conditions to ignore warnings
*/
constructor(ignoreWarnings) {
this._ignoreWarnings = ignoreWarnings;
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap("IgnoreWarningsPlugin", compilation => {
compilation.hooks.processWarnings.tap(
"IgnoreWarningsPlugin",
warnings => {
return warnings.filter(warning => {
return !this._ignoreWarnings.some(ignore =>
ignore(warning, compilation)
);
});
}
);
});
}
}
module.exports = IgnoreWarningsPlugin;

120
assets_old/node_modules/webpack/lib/InitFragment.js generated vendored Normal file
View file

@ -0,0 +1,120 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Florent Cailhol @ooflorent
*/
"use strict";
const { ConcatSource } = require("webpack-sources");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("./Generator").GenerateContext} GenerateContext */
/**
* @param {InitFragment} fragment the init fragment
* @param {number} index index
* @returns {[InitFragment, number]} tuple with both
*/
const extractFragmentIndex = (fragment, index) => [fragment, index];
/**
* @param {[InitFragment, number]} a first pair
* @param {[InitFragment, number]} b second pair
* @returns {number} sort value
*/
const sortFragmentWithIndex = ([a, i], [b, j]) => {
const stageCmp = a.stage - b.stage;
if (stageCmp !== 0) return stageCmp;
const positionCmp = a.position - b.position;
if (positionCmp !== 0) return positionCmp;
return i - j;
};
class InitFragment {
/**
* @param {string|Source} content the source code that will be included as initialization code
* @param {number} stage category of initialization code (contribute to order)
* @param {number} position position in the category (contribute to order)
* @param {string=} key unique key to avoid emitting the same initialization code twice
* @param {string|Source=} endContent the source code that will be included at the end of the module
*/
constructor(content, stage, position, key, endContent) {
this.content = content;
this.stage = stage;
this.position = position;
this.key = key;
this.endContent = endContent;
}
/**
* @param {GenerateContext} generateContext context for generate
* @returns {string|Source} the source code that will be included as initialization code
*/
getContent(generateContext) {
return this.content;
}
/**
* @param {GenerateContext} generateContext context for generate
* @returns {string|Source=} the source code that will be included at the end of the module
*/
getEndContent(generateContext) {
return this.endContent;
}
static addToSource(source, initFragments, generateContext) {
if (initFragments.length > 0) {
// Sort fragments by position. If 2 fragments have the same position,
// use their index.
const sortedFragments = initFragments
.map(extractFragmentIndex)
.sort(sortFragmentWithIndex);
// Deduplicate fragments. If a fragment has no key, it is always included.
const keyedFragments = new Map();
for (const [fragment] of sortedFragments) {
if (typeof fragment.merge === "function") {
const oldValue = keyedFragments.get(fragment.key);
if (oldValue !== undefined) {
keyedFragments.set(
fragment.key || Symbol(),
fragment.merge(oldValue)
);
continue;
}
}
keyedFragments.set(fragment.key || Symbol(), fragment);
}
const concatSource = new ConcatSource();
const endContents = [];
for (const fragment of keyedFragments.values()) {
concatSource.add(fragment.getContent(generateContext));
const endContent = fragment.getEndContent(generateContext);
if (endContent) {
endContents.push(endContent);
}
}
concatSource.add(source);
for (const content of endContents.reverse()) {
concatSource.add(content);
}
return concatSource;
} else {
return source;
}
}
}
InitFragment.prototype.merge = undefined;
InitFragment.STAGE_CONSTANTS = 10;
InitFragment.STAGE_ASYNC_BOUNDARY = 20;
InitFragment.STAGE_HARMONY_EXPORTS = 30;
InitFragment.STAGE_HARMONY_IMPORTS = 40;
InitFragment.STAGE_PROVIDES = 50;
InitFragment.STAGE_ASYNC_DEPENDENCIES = 60;
InitFragment.STAGE_ASYNC_HARMONY_IMPORTS = 70;
module.exports = InitFragment;

View file

@ -0,0 +1,46 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const WebpackError = require("./WebpackError");
const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("./Module")} Module */
class InvalidDependenciesModuleWarning extends WebpackError {
/**
* @param {Module} module module tied to dependency
* @param {Iterable<string>} deps invalid dependencies
*/
constructor(module, deps) {
const orderedDeps = deps ? Array.from(deps).sort() : [];
const depsList = orderedDeps.map(dep => ` * ${JSON.stringify(dep)}`);
super(`Invalid dependencies have been reported by plugins or loaders for this module. All reported dependencies need to be absolute paths.
Invalid dependencies may lead to broken watching and caching.
As best effort we try to convert all invalid values to absolute paths and converting globs into context dependencies, but this is deprecated behavior.
Loaders: Pass absolute paths to this.addDependency (existing files), this.addMissingDependency (not existing files), and this.addContextDependency (directories).
Plugins: Pass absolute paths to fileDependencies (existing files), missingDependencies (not existing files), and contextDependencies (directories).
Globs: They are not supported. Pass absolute path to the directory as context dependencies.
The following invalid values have been reported:
${depsList.slice(0, 3).join("\n")}${
depsList.length > 3 ? "\n * and more ..." : ""
}`);
this.name = "InvalidDependenciesModuleWarning";
this.details = depsList.slice(3).join("\n");
this.module = module;
Error.captureStackTrace(this, this.constructor);
}
}
makeSerializable(
InvalidDependenciesModuleWarning,
"webpack/lib/InvalidDependenciesModuleWarning"
);
module.exports = InvalidDependenciesModuleWarning;

View file

@ -0,0 +1,62 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Sergey Melyukov @smelukov
*/
"use strict";
const InnerGraph = require("./optimize/InnerGraph");
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
class JavascriptMetaInfoPlugin {
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(
"JavascriptMetaInfoPlugin",
(compilation, { normalModuleFactory }) => {
/**
* @param {JavascriptParser} parser the parser
* @returns {void}
*/
const handler = parser => {
parser.hooks.call.for("eval").tap("JavascriptMetaInfoPlugin", () => {
parser.state.module.buildInfo.moduleConcatenationBailout = "eval()";
parser.state.module.buildInfo.usingEval = true;
InnerGraph.bailout(parser.state);
});
parser.hooks.finish.tap("JavascriptMetaInfoPlugin", () => {
let topLevelDeclarations =
parser.state.module.buildInfo.topLevelDeclarations;
if (topLevelDeclarations === undefined) {
topLevelDeclarations = parser.state.module.buildInfo.topLevelDeclarations = new Set();
}
for (const name of parser.scope.definitions.asSet()) {
const freeInfo = parser.getFreeInfoFromVariable(name);
if (freeInfo === undefined) {
topLevelDeclarations.add(name);
}
}
});
};
normalModuleFactory.hooks.parser
.for("javascript/auto")
.tap("JavascriptMetaInfoPlugin", handler);
normalModuleFactory.hooks.parser
.for("javascript/dynamic")
.tap("JavascriptMetaInfoPlugin", handler);
normalModuleFactory.hooks.parser
.for("javascript/esm")
.tap("JavascriptMetaInfoPlugin", handler);
}
);
}
}
module.exports = JavascriptMetaInfoPlugin;

View file

@ -0,0 +1,115 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const asyncLib = require("neo-async");
const EntryDependency = require("./dependencies/EntryDependency");
const { someInIterable } = require("./util/IterableHelpers");
const { compareModulesById } = require("./util/comparators");
const { dirname, mkdirp } = require("./util/fs");
/** @typedef {import("./Compiler")} Compiler */
/**
* @typedef {Object} ManifestModuleData
* @property {string | number} id
* @property {Object} buildMeta
* @property {boolean | string[]} exports
*/
class LibManifestPlugin {
constructor(options) {
this.options = options;
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.emit.tapAsync(
"LibManifestPlugin",
(compilation, callback) => {
const moduleGraph = compilation.moduleGraph;
asyncLib.forEach(
Array.from(compilation.chunks),
(chunk, callback) => {
if (!chunk.canBeInitial()) {
callback();
return;
}
const chunkGraph = compilation.chunkGraph;
const targetPath = compilation.getPath(this.options.path, {
chunk
});
const name =
this.options.name &&
compilation.getPath(this.options.name, {
chunk
});
const content = Object.create(null);
for (const module of chunkGraph.getOrderedChunkModulesIterable(
chunk,
compareModulesById(chunkGraph)
)) {
if (
this.options.entryOnly &&
!someInIterable(
moduleGraph.getIncomingConnections(module),
c => c.dependency instanceof EntryDependency
)
) {
continue;
}
const ident = module.libIdent({
context: this.options.context || compiler.options.context,
associatedObjectForCache: compiler.root
});
if (ident) {
const exportsInfo = moduleGraph.getExportsInfo(module);
const providedExports = exportsInfo.getProvidedExports();
/** @type {ManifestModuleData} */
const data = {
id: chunkGraph.getModuleId(module),
buildMeta: module.buildMeta,
exports: Array.isArray(providedExports)
? providedExports
: undefined
};
content[ident] = data;
}
}
const manifest = {
name,
type: this.options.type,
content
};
// Apply formatting to content if format flag is true;
const manifestContent = this.options.format
? JSON.stringify(manifest, null, 2)
: JSON.stringify(manifest);
const buffer = Buffer.from(manifestContent, "utf8");
mkdirp(
compiler.intermediateFileSystem,
dirname(compiler.intermediateFileSystem, targetPath),
err => {
if (err) return callback(err);
compiler.intermediateFileSystem.writeFile(
targetPath,
buffer,
callback
);
}
);
},
callback
);
}
);
}
}
module.exports = LibManifestPlugin;

View file

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

View file

@ -0,0 +1,68 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
const NormalModule = require("./NormalModule");
const { validate } = require("schema-utils");
const schema = require("../schemas/plugins/LoaderOptionsPlugin.json");
/** @typedef {import("../declarations/plugins/LoaderOptionsPlugin").LoaderOptionsPluginOptions} LoaderOptionsPluginOptions */
/** @typedef {import("./Compiler")} Compiler */
class LoaderOptionsPlugin {
/**
* @param {LoaderOptionsPluginOptions} options options object
*/
constructor(options = {}) {
validate(schema, options, {
name: "Loader Options Plugin",
baseDataPath: "options"
});
if (typeof options !== "object") options = {};
if (!options.test) {
options.test = {
test: () => true
};
}
this.options = options;
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
const options = this.options;
compiler.hooks.compilation.tap("LoaderOptionsPlugin", compilation => {
NormalModule.getCompilationHooks(compilation).loader.tap(
"LoaderOptionsPlugin",
(context, module) => {
const resource = module.resource;
if (!resource) return;
const i = resource.indexOf("?");
if (
ModuleFilenameHelpers.matchObject(
options,
i < 0 ? resource : resource.substr(0, i)
)
) {
for (const key of Object.keys(options)) {
if (key === "include" || key === "exclude" || key === "test") {
continue;
}
context[key] = options[key];
}
}
}
);
});
}
}
module.exports = LoaderOptionsPlugin;

View file

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

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

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

1065
assets_old/node_modules/webpack/lib/Module.js generated vendored Normal file

File diff suppressed because it is too large Load diff

View file

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

View file

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

View file

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

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

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

49
assets_old/node_modules/webpack/lib/ModuleFactory.js generated vendored Normal file
View file

@ -0,0 +1,49 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
/** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */
/** @typedef {import("./Dependency")} Dependency */
/** @typedef {import("./Module")} Module */
/**
* @typedef {Object} ModuleFactoryResult
* @property {Module=} module the created module or unset if no module was created
* @property {Set<string>=} fileDependencies
* @property {Set<string>=} contextDependencies
* @property {Set<string>=} missingDependencies
*/
/**
* @typedef {Object} ModuleFactoryCreateDataContextInfo
* @property {string} issuer
* @property {string | null=} issuerLayer
* @property {string} compiler
*/
/**
* @typedef {Object} ModuleFactoryCreateData
* @property {ModuleFactoryCreateDataContextInfo} contextInfo
* @property {ResolveOptions=} resolveOptions
* @property {string} context
* @property {Dependency[]} dependencies
*/
class ModuleFactory {
/* istanbul ignore next */
/**
* @abstract
* @param {ModuleFactoryCreateData} data data object
* @param {function(Error=, ModuleFactoryResult=): void} callback callback
* @returns {void}
*/
create(data, callback) {
const AbstractMethodError = require("./AbstractMethodError");
throw new AbstractMethodError();
}
}
module.exports = ModuleFactory;

View file

@ -0,0 +1,257 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const createHash = require("./util/createHash");
const memoize = require("./util/memoize");
const ModuleFilenameHelpers = exports;
// TODO webpack 6: consider removing these
ModuleFilenameHelpers.ALL_LOADERS_RESOURCE = "[all-loaders][resource]";
ModuleFilenameHelpers.REGEXP_ALL_LOADERS_RESOURCE = /\[all-?loaders\]\[resource\]/gi;
ModuleFilenameHelpers.LOADERS_RESOURCE = "[loaders][resource]";
ModuleFilenameHelpers.REGEXP_LOADERS_RESOURCE = /\[loaders\]\[resource\]/gi;
ModuleFilenameHelpers.RESOURCE = "[resource]";
ModuleFilenameHelpers.REGEXP_RESOURCE = /\[resource\]/gi;
ModuleFilenameHelpers.ABSOLUTE_RESOURCE_PATH = "[absolute-resource-path]";
// cSpell:words olute
ModuleFilenameHelpers.REGEXP_ABSOLUTE_RESOURCE_PATH = /\[abs(olute)?-?resource-?path\]/gi;
ModuleFilenameHelpers.RESOURCE_PATH = "[resource-path]";
ModuleFilenameHelpers.REGEXP_RESOURCE_PATH = /\[resource-?path\]/gi;
ModuleFilenameHelpers.ALL_LOADERS = "[all-loaders]";
ModuleFilenameHelpers.REGEXP_ALL_LOADERS = /\[all-?loaders\]/gi;
ModuleFilenameHelpers.LOADERS = "[loaders]";
ModuleFilenameHelpers.REGEXP_LOADERS = /\[loaders\]/gi;
ModuleFilenameHelpers.QUERY = "[query]";
ModuleFilenameHelpers.REGEXP_QUERY = /\[query\]/gi;
ModuleFilenameHelpers.ID = "[id]";
ModuleFilenameHelpers.REGEXP_ID = /\[id\]/gi;
ModuleFilenameHelpers.HASH = "[hash]";
ModuleFilenameHelpers.REGEXP_HASH = /\[hash\]/gi;
ModuleFilenameHelpers.NAMESPACE = "[namespace]";
ModuleFilenameHelpers.REGEXP_NAMESPACE = /\[namespace\]/gi;
const getAfter = (strFn, token) => {
return () => {
const str = strFn();
const idx = str.indexOf(token);
return idx < 0 ? "" : str.substr(idx);
};
};
const getBefore = (strFn, token) => {
return () => {
const str = strFn();
const idx = str.lastIndexOf(token);
return idx < 0 ? "" : str.substr(0, idx);
};
};
const getHash = strFn => {
return () => {
const hash = createHash("md4");
hash.update(strFn());
const digest = /** @type {string} */ (hash.digest("hex"));
return digest.substr(0, 4);
};
};
const asRegExp = test => {
if (typeof test === "string") {
test = new RegExp("^" + test.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"));
}
return test;
};
const lazyObject = obj => {
const newObj = {};
for (const key of Object.keys(obj)) {
const fn = obj[key];
Object.defineProperty(newObj, key, {
get: () => fn(),
set: v => {
Object.defineProperty(newObj, key, {
value: v,
enumerable: true,
writable: true
});
},
enumerable: true,
configurable: true
});
}
return newObj;
};
const REGEXP = /\[\\*([\w-]+)\\*\]/gi;
ModuleFilenameHelpers.createFilename = (
module,
options,
{ requestShortener, chunkGraph }
) => {
const opts = {
namespace: "",
moduleFilenameTemplate: "",
...(typeof options === "object"
? options
: {
moduleFilenameTemplate: options
})
};
let absoluteResourcePath;
let hash;
let identifier;
let moduleId;
let shortIdentifier;
if (module === undefined) module = "";
if (typeof module === "string") {
shortIdentifier = memoize(() => requestShortener.shorten(module));
identifier = shortIdentifier;
moduleId = () => "";
absoluteResourcePath = () => module.split("!").pop();
hash = getHash(identifier);
} else {
shortIdentifier = memoize(() =>
module.readableIdentifier(requestShortener)
);
identifier = memoize(() => requestShortener.shorten(module.identifier()));
moduleId = () => chunkGraph.getModuleId(module);
absoluteResourcePath = () => module.identifier().split("!").pop();
hash = getHash(identifier);
}
const resource = memoize(() => shortIdentifier().split("!").pop());
const loaders = getBefore(shortIdentifier, "!");
const allLoaders = getBefore(identifier, "!");
const query = getAfter(resource, "?");
const resourcePath = () => {
const q = query().length;
return q === 0 ? resource() : resource().slice(0, -q);
};
if (typeof opts.moduleFilenameTemplate === "function") {
return opts.moduleFilenameTemplate(
lazyObject({
identifier: identifier,
shortIdentifier: shortIdentifier,
resource: resource,
resourcePath: memoize(resourcePath),
absoluteResourcePath: memoize(absoluteResourcePath),
allLoaders: memoize(allLoaders),
query: memoize(query),
moduleId: memoize(moduleId),
hash: memoize(hash),
namespace: () => opts.namespace
})
);
}
// TODO webpack 6: consider removing alternatives without dashes
/** @type {Map<string, function(): string>} */
const replacements = new Map([
["identifier", identifier],
["short-identifier", shortIdentifier],
["resource", resource],
["resource-path", resourcePath],
// cSpell:words resourcepath
["resourcepath", resourcePath],
["absolute-resource-path", absoluteResourcePath],
["abs-resource-path", absoluteResourcePath],
// cSpell:words absoluteresource
["absoluteresource-path", absoluteResourcePath],
// cSpell:words absresource
["absresource-path", absoluteResourcePath],
// cSpell:words resourcepath
["absolute-resourcepath", absoluteResourcePath],
// cSpell:words resourcepath
["abs-resourcepath", absoluteResourcePath],
// cSpell:words absoluteresourcepath
["absoluteresourcepath", absoluteResourcePath],
// cSpell:words absresourcepath
["absresourcepath", absoluteResourcePath],
["all-loaders", allLoaders],
// cSpell:words allloaders
["allloaders", allLoaders],
["loaders", loaders],
["query", query],
["id", moduleId],
["hash", hash],
["namespace", () => opts.namespace]
]);
// TODO webpack 6: consider removing weird double placeholders
return opts.moduleFilenameTemplate
.replace(ModuleFilenameHelpers.REGEXP_ALL_LOADERS_RESOURCE, "[identifier]")
.replace(
ModuleFilenameHelpers.REGEXP_LOADERS_RESOURCE,
"[short-identifier]"
)
.replace(REGEXP, (match, content) => {
if (content.length + 2 === match.length) {
const replacement = replacements.get(content.toLowerCase());
if (replacement !== undefined) {
return replacement();
}
} else if (match.startsWith("[\\") && match.endsWith("\\]")) {
return `[${match.slice(2, -2)}]`;
}
return match;
});
};
ModuleFilenameHelpers.replaceDuplicates = (array, fn, comparator) => {
const countMap = Object.create(null);
const posMap = Object.create(null);
array.forEach((item, idx) => {
countMap[item] = countMap[item] || [];
countMap[item].push(idx);
posMap[item] = 0;
});
if (comparator) {
Object.keys(countMap).forEach(item => {
countMap[item].sort(comparator);
});
}
return array.map((item, i) => {
if (countMap[item].length > 1) {
if (comparator && countMap[item][0] === i) return item;
return fn(item, i, posMap[item]++);
} else {
return item;
}
});
};
ModuleFilenameHelpers.matchPart = (str, test) => {
if (!test) return true;
test = asRegExp(test);
if (Array.isArray(test)) {
return test.map(asRegExp).some(regExp => regExp.test(str));
} else {
return test.test(str);
}
};
ModuleFilenameHelpers.matchObject = (obj, str) => {
if (obj.test) {
if (!ModuleFilenameHelpers.matchPart(str, obj.test)) {
return false;
}
}
if (obj.include) {
if (!ModuleFilenameHelpers.matchPart(str, obj.include)) {
return false;
}
}
if (obj.exclude) {
if (ModuleFilenameHelpers.matchPart(str, obj.exclude)) {
return false;
}
}
return true;
};

762
assets_old/node_modules/webpack/lib/ModuleGraph.js generated vendored Normal file
View file

@ -0,0 +1,762 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const util = require("util");
const ExportsInfo = require("./ExportsInfo");
const ModuleGraphConnection = require("./ModuleGraphConnection");
const SortableSet = require("./util/SortableSet");
/** @typedef {import("./DependenciesBlock")} DependenciesBlock */
/** @typedef {import("./Dependency")} Dependency */
/** @typedef {import("./ExportsInfo").ExportInfo} ExportInfo */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./ModuleProfile")} ModuleProfile */
/** @typedef {import("./RequestShortener")} RequestShortener */
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
/**
* @callback OptimizationBailoutFunction
* @param {RequestShortener} requestShortener
* @returns {string}
*/
const EMPTY_ARRAY = [];
/**
* @param {SortableSet<ModuleGraphConnection>} set input
* @returns {readonly Map<Module, readonly ModuleGraphConnection[]>} mapped by origin module
*/
const getConnectionsByOriginModule = set => {
const map = new Map();
/** @type {Module | 0} */
let lastModule = 0;
/** @type {ModuleGraphConnection[]} */
let lastList = undefined;
for (const connection of set) {
const { originModule } = connection;
if (lastModule === originModule) {
lastList.push(connection);
} else {
lastModule = originModule;
const list = map.get(originModule);
if (list !== undefined) {
lastList = list;
list.push(connection);
} else {
const list = [connection];
lastList = list;
map.set(originModule, list);
}
}
}
return map;
};
class ModuleGraphModule {
constructor() {
/** @type {SortableSet<ModuleGraphConnection>} */
this.incomingConnections = new SortableSet();
/** @type {Set<ModuleGraphConnection> | undefined} */
this.outgoingConnections = undefined;
/** @type {Module | null} */
this.issuer = undefined;
/** @type {(string | OptimizationBailoutFunction)[]} */
this.optimizationBailout = [];
/** @type {ExportsInfo} */
this.exports = new ExportsInfo();
/** @type {number} */
this.preOrderIndex = null;
/** @type {number} */
this.postOrderIndex = null;
/** @type {number} */
this.depth = null;
/** @type {ModuleProfile} */
this.profile = undefined;
/** @type {boolean} */
this.async = false;
}
}
class ModuleGraphDependency {
constructor() {
/** @type {ModuleGraphConnection} */
this.connection = undefined;
/** @type {Module} */
this.parentModule = undefined;
/** @type {DependenciesBlock} */
this.parentBlock = undefined;
}
}
class ModuleGraph {
constructor() {
/** @type {Map<Dependency, ModuleGraphDependency>} */
this._dependencyMap = new Map();
/** @type {Map<Module, ModuleGraphModule>} */
this._moduleMap = new Map();
/** @type {Map<Module, Set<ModuleGraphConnection>>} */
this._originMap = new Map();
/** @type {Map<any, Object>} */
this._metaMap = new Map();
// Caching
this._cacheModuleGraphModuleKey1 = undefined;
this._cacheModuleGraphModuleValue1 = undefined;
this._cacheModuleGraphModuleKey2 = undefined;
this._cacheModuleGraphModuleValue2 = undefined;
this._cacheModuleGraphDependencyKey = undefined;
this._cacheModuleGraphDependencyValue = undefined;
}
/**
* @param {Module} module the module
* @returns {ModuleGraphModule} the internal module
*/
_getModuleGraphModule(module) {
if (this._cacheModuleGraphModuleKey1 === module)
return this._cacheModuleGraphModuleValue1;
if (this._cacheModuleGraphModuleKey2 === module)
return this._cacheModuleGraphModuleValue2;
let mgm = this._moduleMap.get(module);
if (mgm === undefined) {
mgm = new ModuleGraphModule();
this._moduleMap.set(module, mgm);
}
this._cacheModuleGraphModuleKey2 = this._cacheModuleGraphModuleKey1;
this._cacheModuleGraphModuleValue2 = this._cacheModuleGraphModuleValue1;
this._cacheModuleGraphModuleKey1 = module;
this._cacheModuleGraphModuleValue1 = mgm;
return mgm;
}
/**
* @param {Dependency} dependency the dependency
* @returns {ModuleGraphDependency} the internal dependency
*/
_getModuleGraphDependency(dependency) {
if (this._cacheModuleGraphDependencyKey === dependency)
return this._cacheModuleGraphDependencyValue;
let mgd = this._dependencyMap.get(dependency);
if (mgd === undefined) {
mgd = new ModuleGraphDependency();
this._dependencyMap.set(dependency, mgd);
}
this._cacheModuleGraphDependencyKey = dependency;
this._cacheModuleGraphDependencyValue = mgd;
return mgd;
}
/**
* @param {Dependency} dependency the dependency
* @param {DependenciesBlock} block parent block
* @param {Module} module parent module
* @returns {void}
*/
setParents(dependency, block, module) {
const mgd = this._getModuleGraphDependency(dependency);
mgd.parentBlock = block;
mgd.parentModule = module;
}
/**
* @param {Dependency} dependency the dependency
* @returns {Module} parent module
*/
getParentModule(dependency) {
const mgd = this._getModuleGraphDependency(dependency);
return mgd.parentModule;
}
/**
* @param {Dependency} dependency the dependency
* @returns {DependenciesBlock} parent block
*/
getParentBlock(dependency) {
const mgd = this._getModuleGraphDependency(dependency);
return mgd.parentBlock;
}
/**
* @param {Module} originModule the referencing module
* @param {Dependency} dependency the referencing dependency
* @param {Module} module the referenced module
* @returns {void}
*/
setResolvedModule(originModule, dependency, module) {
const connection = new ModuleGraphConnection(
originModule,
dependency,
module,
undefined,
dependency.weak,
dependency.getCondition(this)
);
const mgd = this._getModuleGraphDependency(dependency);
mgd.connection = connection;
const connections = this._getModuleGraphModule(module).incomingConnections;
connections.add(connection);
const mgm = this._getModuleGraphModule(originModule);
if (mgm.outgoingConnections === undefined) {
mgm.outgoingConnections = new Set();
}
mgm.outgoingConnections.add(connection);
}
/**
* @param {Dependency} dependency the referencing dependency
* @param {Module} module the referenced module
* @returns {void}
*/
updateModule(dependency, module) {
const mgd = this._getModuleGraphDependency(dependency);
if (mgd.connection.module === module) return;
const { connection } = mgd;
const newConnection = connection.clone();
newConnection.module = module;
mgd.connection = newConnection;
connection.setActive(false);
const originMgm = this._getModuleGraphModule(connection.originModule);
originMgm.outgoingConnections.add(newConnection);
const targetMgm = this._getModuleGraphModule(module);
targetMgm.incomingConnections.add(newConnection);
}
/**
* @param {Dependency} dependency the referencing dependency
* @returns {void}
*/
removeConnection(dependency) {
const mgd = this._getModuleGraphDependency(dependency);
const { connection } = mgd;
const targetMgm = this._getModuleGraphModule(connection.module);
targetMgm.incomingConnections.delete(connection);
const originMgm = this._getModuleGraphModule(connection.originModule);
originMgm.outgoingConnections.delete(connection);
mgd.connection = undefined;
}
/**
* @param {Dependency} dependency the referencing dependency
* @param {string} explanation an explanation
* @returns {void}
*/
addExplanation(dependency, explanation) {
const { connection } = this._getModuleGraphDependency(dependency);
connection.addExplanation(explanation);
}
/**
* @param {Module} sourceModule the source module
* @param {Module} targetModule the target module
* @returns {void}
*/
cloneModuleAttributes(sourceModule, targetModule) {
const oldMgm = this._getModuleGraphModule(sourceModule);
const newMgm = this._getModuleGraphModule(targetModule);
newMgm.postOrderIndex = oldMgm.postOrderIndex;
newMgm.preOrderIndex = oldMgm.preOrderIndex;
newMgm.depth = oldMgm.depth;
newMgm.exports = oldMgm.exports;
newMgm.async = oldMgm.async;
}
/**
* @param {Module} module the module
* @returns {void}
*/
removeModuleAttributes(module) {
const mgm = this._getModuleGraphModule(module);
mgm.postOrderIndex = null;
mgm.preOrderIndex = null;
mgm.depth = null;
mgm.async = false;
}
/**
* @returns {void}
*/
removeAllModuleAttributes() {
for (const mgm of this._moduleMap.values()) {
mgm.postOrderIndex = null;
mgm.preOrderIndex = null;
mgm.depth = null;
mgm.async = false;
}
}
/**
* @param {Module} oldModule the old referencing module
* @param {Module} newModule the new referencing module
* @param {function(ModuleGraphConnection): boolean} filterConnection filter predicate for replacement
* @returns {void}
*/
moveModuleConnections(oldModule, newModule, filterConnection) {
if (oldModule === newModule) return;
const oldMgm = this._getModuleGraphModule(oldModule);
const newMgm = this._getModuleGraphModule(newModule);
// Outgoing connections
const oldConnections = oldMgm.outgoingConnections;
if (oldConnections !== undefined) {
if (newMgm.outgoingConnections === undefined) {
newMgm.outgoingConnections = new Set();
}
const newConnections = newMgm.outgoingConnections;
for (const connection of oldConnections) {
if (filterConnection(connection)) {
connection.originModule = newModule;
newConnections.add(connection);
oldConnections.delete(connection);
}
}
}
// Incoming connections
const oldConnections2 = oldMgm.incomingConnections;
const newConnections2 = newMgm.incomingConnections;
for (const connection of oldConnections2) {
if (filterConnection(connection)) {
connection.module = newModule;
newConnections2.add(connection);
oldConnections2.delete(connection);
}
}
}
/**
* @param {Module} oldModule the old referencing module
* @param {Module} newModule the new referencing module
* @param {function(ModuleGraphConnection): boolean} filterConnection filter predicate for replacement
* @returns {void}
*/
copyOutgoingModuleConnections(oldModule, newModule, filterConnection) {
if (oldModule === newModule) return;
const oldMgm = this._getModuleGraphModule(oldModule);
const newMgm = this._getModuleGraphModule(newModule);
// Outgoing connections
const oldConnections = oldMgm.outgoingConnections;
if (oldConnections !== undefined) {
if (newMgm.outgoingConnections === undefined) {
newMgm.outgoingConnections = new Set();
}
const newConnections = newMgm.outgoingConnections;
for (const connection of oldConnections) {
if (filterConnection(connection)) {
const newConnection = connection.clone();
newConnection.originModule = newModule;
newConnections.add(newConnection);
if (newConnection.module !== undefined) {
const otherMgm = this._getModuleGraphModule(newConnection.module);
otherMgm.incomingConnections.add(newConnection);
}
}
}
}
}
/**
* @param {Module} module the referenced module
* @param {string} explanation an explanation why it's referenced
* @returns {void}
*/
addExtraReason(module, explanation) {
const connections = this._getModuleGraphModule(module).incomingConnections;
connections.add(new ModuleGraphConnection(null, null, module, explanation));
}
/**
* @param {Dependency} dependency the dependency to look for a referenced module
* @returns {Module} the referenced module
*/
getResolvedModule(dependency) {
const { connection } = this._getModuleGraphDependency(dependency);
return connection !== undefined ? connection.resolvedModule : null;
}
/**
* @param {Dependency} dependency the dependency to look for a referenced module
* @returns {ModuleGraphConnection | undefined} the connection
*/
getConnection(dependency) {
const { connection } = this._getModuleGraphDependency(dependency);
return connection;
}
/**
* @param {Dependency} dependency the dependency to look for a referenced module
* @returns {Module} the referenced module
*/
getModule(dependency) {
const { connection } = this._getModuleGraphDependency(dependency);
return connection !== undefined ? connection.module : null;
}
/**
* @param {Dependency} dependency the dependency to look for a referencing module
* @returns {Module} the referencing module
*/
getOrigin(dependency) {
const { connection } = this._getModuleGraphDependency(dependency);
return connection !== undefined ? connection.originModule : null;
}
/**
* @param {Dependency} dependency the dependency to look for a referencing module
* @returns {Module} the original referencing module
*/
getResolvedOrigin(dependency) {
const { connection } = this._getModuleGraphDependency(dependency);
return connection !== undefined ? connection.resolvedOriginModule : null;
}
/**
* @param {Module} module the module
* @returns {Iterable<ModuleGraphConnection>} reasons why a module is included
*/
getIncomingConnections(module) {
const connections = this._getModuleGraphModule(module).incomingConnections;
return connections;
}
/**
* @param {Module} module the module
* @returns {Iterable<ModuleGraphConnection>} list of outgoing connections
*/
getOutgoingConnections(module) {
const connections = this._getModuleGraphModule(module).outgoingConnections;
return connections === undefined ? EMPTY_ARRAY : connections;
}
/**
* @param {Module} module the module
* @returns {readonly Map<Module, readonly ModuleGraphConnection[]>} reasons why a module is included, in a map by source module
*/
getIncomingConnectionsByOriginModule(module) {
const connections = this._getModuleGraphModule(module).incomingConnections;
return connections.getFromUnorderedCache(getConnectionsByOriginModule);
}
/**
* @param {Module} module the module
* @returns {ModuleProfile | null} the module profile
*/
getProfile(module) {
const mgm = this._getModuleGraphModule(module);
return mgm.profile;
}
/**
* @param {Module} module the module
* @param {ModuleProfile | null} profile the module profile
* @returns {void}
*/
setProfile(module, profile) {
const mgm = this._getModuleGraphModule(module);
mgm.profile = profile;
}
/**
* @param {Module} module the module
* @returns {Module | null} the issuer module
*/
getIssuer(module) {
const mgm = this._getModuleGraphModule(module);
return mgm.issuer;
}
/**
* @param {Module} module the module
* @param {Module | null} issuer the issuer module
* @returns {void}
*/
setIssuer(module, issuer) {
const mgm = this._getModuleGraphModule(module);
mgm.issuer = issuer;
}
/**
* @param {Module} module the module
* @param {Module | null} issuer the issuer module
* @returns {void}
*/
setIssuerIfUnset(module, issuer) {
const mgm = this._getModuleGraphModule(module);
if (mgm.issuer === undefined) mgm.issuer = issuer;
}
/**
* @param {Module} module the module
* @returns {(string | OptimizationBailoutFunction)[]} optimization bailouts
*/
getOptimizationBailout(module) {
const mgm = this._getModuleGraphModule(module);
return mgm.optimizationBailout;
}
/**
* @param {Module} module the module
* @returns {true | string[] | null} the provided exports
*/
getProvidedExports(module) {
const mgm = this._getModuleGraphModule(module);
return mgm.exports.getProvidedExports();
}
/**
* @param {Module} module the module
* @param {string | string[]} exportName a name of an export
* @returns {boolean | null} true, if the export is provided by the module.
* null, if it's unknown.
* false, if it's not provided.
*/
isExportProvided(module, exportName) {
const mgm = this._getModuleGraphModule(module);
const result = mgm.exports.isExportProvided(exportName);
return result === undefined ? null : result;
}
/**
* @param {Module} module the module
* @returns {ExportsInfo} info about the exports
*/
getExportsInfo(module) {
const mgm = this._getModuleGraphModule(module);
return mgm.exports;
}
/**
* @param {Module} module the module
* @param {string} exportName the export
* @returns {ExportInfo} info about the export
*/
getExportInfo(module, exportName) {
const mgm = this._getModuleGraphModule(module);
return mgm.exports.getExportInfo(exportName);
}
/**
* @param {Module} module the module
* @param {string} exportName the export
* @returns {ExportInfo} info about the export (do not modify)
*/
getReadOnlyExportInfo(module, exportName) {
const mgm = this._getModuleGraphModule(module);
return mgm.exports.getReadOnlyExportInfo(exportName);
}
/**
* @param {Module} module the module
* @param {RuntimeSpec} runtime the runtime
* @returns {false | true | SortableSet<string> | null} the used exports
* false: module is not used at all.
* true: the module namespace/object export is used.
* SortableSet<string>: these export names are used.
* empty SortableSet<string>: module is used but no export.
* null: unknown, worst case should be assumed.
*/
getUsedExports(module, runtime) {
const mgm = this._getModuleGraphModule(module);
return mgm.exports.getUsedExports(runtime);
}
/**
* @param {Module} module the module
* @returns {number} the index of the module
*/
getPreOrderIndex(module) {
const mgm = this._getModuleGraphModule(module);
return mgm.preOrderIndex;
}
/**
* @param {Module} module the module
* @returns {number} the index of the module
*/
getPostOrderIndex(module) {
const mgm = this._getModuleGraphModule(module);
return mgm.postOrderIndex;
}
/**
* @param {Module} module the module
* @param {number} index the index of the module
* @returns {void}
*/
setPreOrderIndex(module, index) {
const mgm = this._getModuleGraphModule(module);
mgm.preOrderIndex = index;
}
/**
* @param {Module} module the module
* @param {number} index the index of the module
* @returns {boolean} true, if the index was set
*/
setPreOrderIndexIfUnset(module, index) {
const mgm = this._getModuleGraphModule(module);
if (mgm.preOrderIndex === null) {
mgm.preOrderIndex = index;
return true;
}
return false;
}
/**
* @param {Module} module the module
* @param {number} index the index of the module
* @returns {void}
*/
setPostOrderIndex(module, index) {
const mgm = this._getModuleGraphModule(module);
mgm.postOrderIndex = index;
}
/**
* @param {Module} module the module
* @param {number} index the index of the module
* @returns {boolean} true, if the index was set
*/
setPostOrderIndexIfUnset(module, index) {
const mgm = this._getModuleGraphModule(module);
if (mgm.postOrderIndex === null) {
mgm.postOrderIndex = index;
return true;
}
return false;
}
/**
* @param {Module} module the module
* @returns {number} the depth of the module
*/
getDepth(module) {
const mgm = this._getModuleGraphModule(module);
return mgm.depth;
}
/**
* @param {Module} module the module
* @param {number} depth the depth of the module
* @returns {void}
*/
setDepth(module, depth) {
const mgm = this._getModuleGraphModule(module);
mgm.depth = depth;
}
/**
* @param {Module} module the module
* @param {number} depth the depth of the module
* @returns {boolean} true, if the depth was set
*/
setDepthIfLower(module, depth) {
const mgm = this._getModuleGraphModule(module);
if (mgm.depth === null || mgm.depth > depth) {
mgm.depth = depth;
return true;
}
return false;
}
/**
* @param {Module} module the module
* @returns {boolean} true, if the module is async
*/
isAsync(module) {
const mgm = this._getModuleGraphModule(module);
return mgm.async;
}
/**
* @param {Module} module the module
* @returns {void}
*/
setAsync(module) {
const mgm = this._getModuleGraphModule(module);
mgm.async = true;
}
/**
* @param {any} thing any thing
* @returns {Object} metadata
*/
getMeta(thing) {
let meta = this._metaMap.get(thing);
if (meta === undefined) {
meta = Object.create(null);
this._metaMap.set(thing, meta);
}
return meta;
}
/**
* @param {any} thing any thing
* @returns {Object} metadata
*/
getMetaIfExisting(thing) {
return this._metaMap.get(thing);
}
// TODO remove in webpack 6
/**
* @param {Module} module the module
* @param {string} deprecateMessage message for the deprecation message
* @param {string} deprecationCode code for the deprecation
* @returns {ModuleGraph} the module graph
*/
static getModuleGraphForModule(module, deprecateMessage, deprecationCode) {
const fn = deprecateMap.get(deprecateMessage);
if (fn) return fn(module);
const newFn = util.deprecate(
/**
* @param {Module} module the module
* @returns {ModuleGraph} the module graph
*/
module => {
const moduleGraph = moduleGraphForModuleMap.get(module);
if (!moduleGraph)
throw new Error(
deprecateMessage +
"There was no ModuleGraph assigned to the Module for backward-compat (Use the new API)"
);
return moduleGraph;
},
deprecateMessage + ": Use new ModuleGraph API",
deprecationCode
);
deprecateMap.set(deprecateMessage, newFn);
return newFn(module);
}
// TODO remove in webpack 6
/**
* @param {Module} module the module
* @param {ModuleGraph} moduleGraph the module graph
* @returns {void}
*/
static setModuleGraphForModule(module, moduleGraph) {
moduleGraphForModuleMap.set(module, moduleGraph);
}
// TODO remove in webpack 6
/**
* @param {Module} module the module
* @returns {void}
*/
static clearModuleGraphForModule(module) {
moduleGraphForModuleMap.delete(module);
}
}
// TODO remove in webpack 6
/** @type {WeakMap<Module, ModuleGraph>} */
const moduleGraphForModuleMap = new WeakMap();
// TODO remove in webpack 6
/** @type {Map<string, (module: Module) => ModuleGraph>} */
const deprecateMap = new Map();
module.exports = ModuleGraph;
module.exports.ModuleGraphConnection = ModuleGraphConnection;

View file

@ -0,0 +1,187 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
/** @typedef {import("./Dependency")} Dependency */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
/**
* Module itself is not connected, but transitive modules are connected transitively.
*/
const TRANSITIVE_ONLY = Symbol("transitive only");
/**
* While determining the active state, this flag is used to signal a circular connection.
*/
const CIRCULAR_CONNECTION = Symbol("circular connection");
/** @typedef {boolean | typeof TRANSITIVE_ONLY | typeof CIRCULAR_CONNECTION} ConnectionState */
/**
* @param {ConnectionState} a first
* @param {ConnectionState} b second
* @returns {ConnectionState} merged
*/
const addConnectionStates = (a, b) => {
if (a === true || b === true) return true;
if (a === false) return b;
if (b === false) return a;
if (a === TRANSITIVE_ONLY) return b;
if (b === TRANSITIVE_ONLY) return a;
return a;
};
/**
* @param {ConnectionState} a first
* @param {ConnectionState} b second
* @returns {ConnectionState} intersected
*/
const intersectConnectionStates = (a, b) => {
if (a === false || b === false) return false;
if (a === true) return b;
if (b === true) return a;
if (a === CIRCULAR_CONNECTION) return b;
if (b === CIRCULAR_CONNECTION) return a;
return a;
};
class ModuleGraphConnection {
/**
* @param {Module|null} originModule the referencing module
* @param {Dependency|null} dependency the referencing dependency
* @param {Module} module the referenced module
* @param {string=} explanation some extra detail
* @param {boolean=} weak the reference is weak
* @param {false | function(ModuleGraphConnection, RuntimeSpec): ConnectionState=} condition condition for the connection
*/
constructor(
originModule,
dependency,
module,
explanation,
weak = false,
condition = undefined
) {
this.originModule = originModule;
this.resolvedOriginModule = originModule;
this.dependency = dependency;
this.resolvedModule = module;
this.module = module;
this.weak = weak;
this.conditional = !!condition;
this._active = condition !== false;
/** @type {function(ModuleGraphConnection, RuntimeSpec): ConnectionState} */
this.condition = condition || undefined;
/** @type {Set<string>} */
this.explanations = undefined;
if (explanation) {
this.explanations = new Set();
this.explanations.add(explanation);
}
}
clone() {
const clone = new ModuleGraphConnection(
this.resolvedOriginModule,
this.dependency,
this.resolvedModule,
undefined,
this.weak,
this.condition
);
clone.originModule = this.originModule;
clone.module = this.module;
clone.conditional = this.conditional;
clone._active = this._active;
if (this.explanations) clone.explanations = new Set(this.explanations);
return clone;
}
/**
* @param {function(ModuleGraphConnection, RuntimeSpec): ConnectionState} condition condition for the connection
* @returns {void}
*/
addCondition(condition) {
if (this.conditional) {
const old = this.condition;
this.condition = (c, r) =>
intersectConnectionStates(old(c, r), condition(c, r));
} else if (this._active) {
this.conditional = true;
this.condition = condition;
}
}
/**
* @param {string} explanation the explanation to add
* @returns {void}
*/
addExplanation(explanation) {
if (this.explanations === undefined) {
this.explanations = new Set();
}
this.explanations.add(explanation);
}
get explanation() {
if (this.explanations === undefined) return "";
return Array.from(this.explanations).join(" ");
}
// TODO webpack 5 remove
get active() {
throw new Error("Use getActiveState instead");
}
/**
* @param {RuntimeSpec} runtime the runtime
* @returns {boolean} true, if the connection is active
*/
isActive(runtime) {
if (!this.conditional) return this._active;
return this.condition(this, runtime) !== false;
}
/**
* @param {RuntimeSpec} runtime the runtime
* @returns {boolean} true, if the connection is active
*/
isTargetActive(runtime) {
if (!this.conditional) return this._active;
return this.condition(this, runtime) === true;
}
/**
* @param {RuntimeSpec} runtime the runtime
* @returns {ConnectionState} true: fully active, false: inactive, TRANSITIVE: direct module inactive, but transitive connection maybe active
*/
getActiveState(runtime) {
if (!this.conditional) return this._active;
return this.condition(this, runtime);
}
/**
* @param {boolean} value active or not
* @returns {void}
*/
setActive(value) {
this.conditional = false;
this._active = value;
}
set active(value) {
throw new Error("Use setActive instead");
}
}
/** @typedef {typeof TRANSITIVE_ONLY} TRANSITIVE_ONLY */
/** @typedef {typeof CIRCULAR_CONNECTION} CIRCULAR_CONNECTION */
module.exports = ModuleGraphConnection;
module.exports.addConnectionStates = addConnectionStates;
module.exports.TRANSITIVE_ONLY = /** @type {typeof TRANSITIVE_ONLY} */ (TRANSITIVE_ONLY);
module.exports.CIRCULAR_CONNECTION = /** @type {typeof CIRCULAR_CONNECTION} */ (CIRCULAR_CONNECTION);

View file

@ -0,0 +1,256 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { ConcatSource, RawSource, CachedSource } = require("webpack-sources");
const { UsageState } = require("./ExportsInfo");
const Template = require("./Template");
const JavascriptModulesPlugin = require("./javascript/JavascriptModulesPlugin");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./ExportsInfo")} ExportsInfo */
/** @typedef {import("./ExportsInfo").ExportInfo} ExportInfo */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
/** @typedef {import("./ModuleTemplate")} ModuleTemplate */
/** @typedef {import("./RequestShortener")} RequestShortener */
const joinIterableWithComma = iterable => {
// This is more performant than Array.from().join(", ")
// as it doesn't create an array
let str = "";
let first = true;
for (const item of iterable) {
if (first) {
first = false;
} else {
str += ", ";
}
str += item;
}
return str;
};
/**
* @param {ConcatSource} source output
* @param {string} indent spacing
* @param {ExportsInfo} exportsInfo data
* @param {ModuleGraph} moduleGraph moduleGraph
* @param {RequestShortener} requestShortener requestShortener
* @param {Set<ExportInfo>} alreadyPrinted deduplication set
* @returns {void}
*/
const printExportsInfoToSource = (
source,
indent,
exportsInfo,
moduleGraph,
requestShortener,
alreadyPrinted = new Set()
) => {
const otherExportsInfo = exportsInfo.otherExportsInfo;
let alreadyPrintedExports = 0;
// determine exports to print
const printedExports = [];
for (const exportInfo of exportsInfo.orderedExports) {
if (!alreadyPrinted.has(exportInfo)) {
alreadyPrinted.add(exportInfo);
printedExports.push(exportInfo);
} else {
alreadyPrintedExports++;
}
}
let showOtherExports = false;
if (!alreadyPrinted.has(otherExportsInfo)) {
alreadyPrinted.add(otherExportsInfo);
showOtherExports = true;
} else {
alreadyPrintedExports++;
}
// print the exports
for (const exportInfo of printedExports) {
const target = exportInfo.getTarget(moduleGraph);
source.add(
Template.toComment(
`${indent}export ${JSON.stringify(exportInfo.name).slice(
1,
-1
)} [${exportInfo.getProvidedInfo()}] [${exportInfo.getUsedInfo()}] [${exportInfo.getRenameInfo()}]${
target
? ` -> ${target.module.readableIdentifier(requestShortener)}${
target.export
? ` .${target.export
.map(e => JSON.stringify(e).slice(1, -1))
.join(".")}`
: ""
}`
: ""
}`
) + "\n"
);
if (exportInfo.exportsInfo) {
printExportsInfoToSource(
source,
indent + " ",
exportInfo.exportsInfo,
moduleGraph,
requestShortener,
alreadyPrinted
);
}
}
if (alreadyPrintedExports) {
source.add(
Template.toComment(
`${indent}... (${alreadyPrintedExports} already listed exports)`
) + "\n"
);
}
if (showOtherExports) {
const target = otherExportsInfo.getTarget(moduleGraph);
if (
target ||
otherExportsInfo.provided !== false ||
otherExportsInfo.getUsed(undefined) !== UsageState.Unused
) {
const title =
printedExports.length > 0 || alreadyPrintedExports > 0
? "other exports"
: "exports";
source.add(
Template.toComment(
`${indent}${title} [${otherExportsInfo.getProvidedInfo()}] [${otherExportsInfo.getUsedInfo()}]${
target
? ` -> ${target.module.readableIdentifier(requestShortener)}`
: ""
}`
) + "\n"
);
}
}
};
/** @type {WeakMap<RequestShortener, WeakMap<Module, { header: RawSource, full: WeakMap<Source, CachedSource> }>>} */
const caches = new WeakMap();
class ModuleInfoHeaderPlugin {
/**
* @param {boolean=} verbose add more information like exports, runtime requirements and bailouts
*/
constructor(verbose = true) {
this._verbose = verbose;
}
/**
* @param {Compiler} compiler the compiler
* @returns {void}
*/
apply(compiler) {
const { _verbose: verbose } = this;
compiler.hooks.compilation.tap("ModuleInfoHeaderPlugin", compilation => {
const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation);
hooks.renderModulePackage.tap(
"ModuleInfoHeaderPlugin",
(
moduleSource,
module,
{ chunk, chunkGraph, moduleGraph, runtimeTemplate }
) => {
const { requestShortener } = runtimeTemplate;
let cacheEntry;
let cache = caches.get(requestShortener);
if (cache === undefined) {
caches.set(requestShortener, (cache = new WeakMap()));
cache.set(
module,
(cacheEntry = { header: undefined, full: new WeakMap() })
);
} else {
cacheEntry = cache.get(module);
if (cacheEntry === undefined) {
cache.set(
module,
(cacheEntry = { header: undefined, full: new WeakMap() })
);
} else if (!verbose) {
const cachedSource = cacheEntry.full.get(moduleSource);
if (cachedSource !== undefined) return cachedSource;
}
}
const source = new ConcatSource();
let header = cacheEntry.header;
if (header === undefined) {
const req = module.readableIdentifier(requestShortener);
const reqStr = req.replace(/\*\//g, "*_/");
const reqStrStar = "*".repeat(reqStr.length);
const headerStr = `/*!****${reqStrStar}****!*\\\n !*** ${reqStr} ***!\n \\****${reqStrStar}****/\n`;
header = new RawSource(headerStr);
cacheEntry.header = header;
}
source.add(header);
if (verbose) {
const exportsType = module.buildMeta.exportsType;
source.add(
Template.toComment(
exportsType
? `${exportsType} exports`
: "unknown exports (runtime-defined)"
) + "\n"
);
if (exportsType) {
const exportsInfo = moduleGraph.getExportsInfo(module);
printExportsInfoToSource(
source,
"",
exportsInfo,
moduleGraph,
requestShortener
);
}
source.add(
Template.toComment(
`runtime requirements: ${joinIterableWithComma(
chunkGraph.getModuleRuntimeRequirements(module, chunk.runtime)
)}`
) + "\n"
);
const optimizationBailout = moduleGraph.getOptimizationBailout(
module
);
if (optimizationBailout) {
for (const text of optimizationBailout) {
let code;
if (typeof text === "function") {
code = text(requestShortener);
} else {
code = text;
}
source.add(Template.toComment(`${code}`) + "\n");
}
}
source.add(moduleSource);
return source;
} else {
source.add(moduleSource);
const cachedSource = new CachedSource(source);
cacheEntry.full.set(moduleSource, cachedSource);
return cachedSource;
}
}
);
hooks.chunkHash.tap("ModuleInfoHeaderPlugin", (chunk, hash) => {
hash.update("ModuleInfoHeaderPlugin");
hash.update("1");
});
});
}
}
module.exports = ModuleInfoHeaderPlugin;

View file

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

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

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

107
assets_old/node_modules/webpack/lib/ModuleProfile.js generated vendored Normal file
View file

@ -0,0 +1,107 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
class ModuleProfile {
constructor() {
this.startTime = Date.now();
this.factoryStartTime = 0;
this.factoryEndTime = 0;
this.factory = 0;
this.factoryParallelismFactor = 0;
this.restoringStartTime = 0;
this.restoringEndTime = 0;
this.restoring = 0;
this.restoringParallelismFactor = 0;
this.integrationStartTime = 0;
this.integrationEndTime = 0;
this.integration = 0;
this.integrationParallelismFactor = 0;
this.buildingStartTime = 0;
this.buildingEndTime = 0;
this.building = 0;
this.buildingParallelismFactor = 0;
this.storingStartTime = 0;
this.storingEndTime = 0;
this.storing = 0;
this.storingParallelismFactor = 0;
this.additionalFactoryTimes = undefined;
this.additionalFactories = 0;
this.additionalFactoriesParallelismFactor = 0;
/** @deprecated */
this.additionalIntegration = 0;
}
markFactoryStart() {
this.factoryStartTime = Date.now();
}
markFactoryEnd() {
this.factoryEndTime = Date.now();
this.factory = this.factoryEndTime - this.factoryStartTime;
}
markRestoringStart() {
this.restoringStartTime = Date.now();
}
markRestoringEnd() {
this.restoringEndTime = Date.now();
this.restoring = this.restoringEndTime - this.restoringStartTime;
}
markIntegrationStart() {
this.integrationStartTime = Date.now();
}
markIntegrationEnd() {
this.integrationEndTime = Date.now();
this.integration = this.integrationEndTime - this.integrationStartTime;
}
markBuildingStart() {
this.buildingStartTime = Date.now();
}
markBuildingEnd() {
this.buildingEndTime = Date.now();
this.building = this.buildingEndTime - this.buildingStartTime;
}
markStoringStart() {
this.storingStartTime = Date.now();
}
markStoringEnd() {
this.storingEndTime = Date.now();
this.storing = this.storingEndTime - this.storingStartTime;
}
// This depends on timing so we ignore it for coverage
/* istanbul ignore next */
/**
* Merge this profile into another one
* @param {ModuleProfile} realProfile the profile to merge into
* @returns {void}
*/
mergeInto(realProfile) {
realProfile.additionalFactories = this.factory;
(realProfile.additionalFactoryTimes =
realProfile.additionalFactoryTimes || []).push({
start: this.factoryStartTime,
end: this.factoryEndTime
});
}
}
module.exports = ModuleProfile;

View file

@ -0,0 +1,44 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const WebpackError = require("./WebpackError");
/** @typedef {import("./Module")} Module */
class ModuleRestoreError extends WebpackError {
/**
* @param {Module} module module tied to dependency
* @param {string | Error} err error thrown
*/
constructor(module, err) {
let message = "Module restore failed: ";
let details = undefined;
if (err !== null && typeof err === "object") {
if (typeof err.stack === "string" && err.stack) {
const stack = err.stack;
message += stack;
} else if (typeof err.message === "string" && err.message) {
message += err.message;
} else {
message += err;
}
} else {
message += String(err);
}
super(message);
this.name = "ModuleRestoreError";
this.details = details;
this.module = module;
this.error = err;
Error.captureStackTrace(this, this.constructor);
}
}
module.exports = ModuleRestoreError;

View file

@ -0,0 +1,44 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const WebpackError = require("./WebpackError");
/** @typedef {import("./Module")} Module */
class ModuleStoreError extends WebpackError {
/**
* @param {Module} module module tied to dependency
* @param {string | Error} err error thrown
*/
constructor(module, err) {
let message = "Module storing failed: ";
let details = undefined;
if (err !== null && typeof err === "object") {
if (typeof err.stack === "string" && err.stack) {
const stack = err.stack;
message += stack;
} else if (typeof err.message === "string" && err.message) {
message += err.message;
} else {
message += err;
}
} else {
message += String(err);
}
super(message);
this.name = "ModuleStoreError";
this.details = details;
this.module = module;
this.error = err;
Error.captureStackTrace(this, this.constructor);
}
}
module.exports = ModuleStoreError;

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

@ -0,0 +1,151 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const util = require("util");
const memoize = require("./util/memoize");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
/** @typedef {import("./util/Hash")} Hash */
const getJavascriptModulesPlugin = memoize(() =>
require("./javascript/JavascriptModulesPlugin")
);
/**
* @typedef {Object} RenderContext
* @property {Chunk} chunk the chunk
* @property {DependencyTemplates} dependencyTemplates the dependency templates
* @property {RuntimeTemplate} runtimeTemplate the runtime template
* @property {ModuleGraph} moduleGraph the module graph
* @property {ChunkGraph} chunkGraph the chunk graph
*/
// TODO webpack 6: remove this class
class ModuleTemplate {
/**
* @param {RuntimeTemplate} runtimeTemplate the runtime template
* @param {Compilation} compilation the compilation
*/
constructor(runtimeTemplate, compilation) {
this._runtimeTemplate = runtimeTemplate;
this.type = "javascript";
this.hooks = Object.freeze({
content: {
tap: util.deprecate(
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
.renderModuleContent.tap(
options,
(source, module, renderContext) =>
fn(
source,
module,
renderContext,
renderContext.dependencyTemplates
)
);
},
"ModuleTemplate.hooks.content is deprecated (use JavascriptModulesPlugin.getCompilationHooks().renderModuleContent instead)",
"DEP_MODULE_TEMPLATE_CONTENT"
)
},
module: {
tap: util.deprecate(
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
.renderModuleContent.tap(
options,
(source, module, renderContext) =>
fn(
source,
module,
renderContext,
renderContext.dependencyTemplates
)
);
},
"ModuleTemplate.hooks.module is deprecated (use JavascriptModulesPlugin.getCompilationHooks().renderModuleContent instead)",
"DEP_MODULE_TEMPLATE_MODULE"
)
},
render: {
tap: util.deprecate(
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
.renderModuleContainer.tap(
options,
(source, module, renderContext) =>
fn(
source,
module,
renderContext,
renderContext.dependencyTemplates
)
);
},
"ModuleTemplate.hooks.render is deprecated (use JavascriptModulesPlugin.getCompilationHooks().renderModuleContainer instead)",
"DEP_MODULE_TEMPLATE_RENDER"
)
},
package: {
tap: util.deprecate(
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
.renderModulePackage.tap(
options,
(source, module, renderContext) =>
fn(
source,
module,
renderContext,
renderContext.dependencyTemplates
)
);
},
"ModuleTemplate.hooks.package is deprecated (use JavascriptModulesPlugin.getCompilationHooks().renderModulePackage instead)",
"DEP_MODULE_TEMPLATE_PACKAGE"
)
},
hash: {
tap: util.deprecate(
(options, fn) => {
compilation.hooks.fullHash.tap(options, fn);
},
"ModuleTemplate.hooks.hash is deprecated (use Compilation.hooks.fullHash instead)",
"DEP_MODULE_TEMPLATE_HASH"
)
}
});
}
}
Object.defineProperty(ModuleTemplate.prototype, "runtimeTemplate", {
get: util.deprecate(
/**
* @this {ModuleTemplate}
* @returns {TODO} output options
*/
function () {
return this._runtimeTemplate;
},
"ModuleTemplate.runtimeTemplate is deprecated (use Compilation.runtimeTemplate instead)",
"DEP_WEBPACK_CHUNK_TEMPLATE_OUTPUT_OPTIONS"
)
});
module.exports = ModuleTemplate;

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

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

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

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

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

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

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

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

View file

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

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

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

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

@ -0,0 +1,133 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const RuntimeGlobals = require("./RuntimeGlobals");
const CachedConstDependency = require("./dependencies/CachedConstDependency");
const ConstDependency = require("./dependencies/ConstDependency");
const {
evaluateToString,
expressionIsUnsupported
} = require("./javascript/JavascriptParserHelpers");
const { relative } = require("./util/fs");
const { parseResource } = require("./util/identifier");
/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Dependency")} Dependency */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
class NodeStuffPlugin {
constructor(options) {
this.options = options;
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
const options = this.options;
compiler.hooks.compilation.tap(
"NodeStuffPlugin",
(compilation, { normalModuleFactory }) => {
const handler = (parser, parserOptions) => {
if (parserOptions.node === false) return;
let localOptions = options;
if (parserOptions.node) {
localOptions = { ...localOptions, ...parserOptions.node };
}
if (localOptions.global) {
parser.hooks.expression
.for("global")
.tap("NodeStuffPlugin", expr => {
const dep = new ConstDependency(
RuntimeGlobals.global,
expr.range,
[RuntimeGlobals.global]
);
dep.loc = expr.loc;
parser.state.module.addPresentationalDependency(dep);
});
}
const setModuleConstant = (expressionName, fn) => {
parser.hooks.expression
.for(expressionName)
.tap("NodeStuffPlugin", expr => {
const dep = new CachedConstDependency(
JSON.stringify(fn(parser.state.module)),
expr.range,
expressionName
);
dep.loc = expr.loc;
parser.state.module.addPresentationalDependency(dep);
return true;
});
};
const setConstant = (expressionName, value) =>
setModuleConstant(expressionName, () => value);
const context = compiler.context;
if (localOptions.__filename) {
if (localOptions.__filename === "mock") {
setConstant("__filename", "/index.js");
} else if (localOptions.__filename === true) {
setModuleConstant("__filename", module =>
relative(compiler.inputFileSystem, context, module.resource)
);
}
parser.hooks.evaluateIdentifier
.for("__filename")
.tap("NodeStuffPlugin", expr => {
if (!parser.state.module) return;
const resource = parseResource(parser.state.module.resource);
return evaluateToString(resource.path)(expr);
});
}
if (localOptions.__dirname) {
if (localOptions.__dirname === "mock") {
setConstant("__dirname", "/");
} else if (localOptions.__dirname === true) {
setModuleConstant("__dirname", module =>
relative(compiler.inputFileSystem, context, module.context)
);
}
parser.hooks.evaluateIdentifier
.for("__dirname")
.tap("NodeStuffPlugin", expr => {
if (!parser.state.module) return;
return evaluateToString(parser.state.module.context)(expr);
});
}
parser.hooks.expression
.for("require.extensions")
.tap(
"NodeStuffPlugin",
expressionIsUnsupported(
parser,
"require.extensions is not supported by webpack. Use a loader instead."
)
);
};
normalModuleFactory.hooks.parser
.for("javascript/auto")
.tap("NodeStuffPlugin", handler);
normalModuleFactory.hooks.parser
.for("javascript/dynamic")
.tap("NodeStuffPlugin", handler);
}
);
}
}
module.exports = NodeStuffPlugin;

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